Writing a query that will handle three different labels - sql

I have 3 different drop down options. If I select one option at a time it works, but on selecting more than one it will throw an error. The three labels refer to three different versions. Everything works but when I select more than one option in the drop down it crashes. Need help understanding it why
The three parameters are
Select all:
Report1
Report2
Report3
Here my query:
SELECT
ServerInfo.Version,
ServerInfo.Type,
ProjInfo.ProjName,
ServerInfo.ServName
FROM
ProjInfo, ServerInfo
WHERE ServerInfo.Version LIKE('%'+#ServerReport+'%')
Incorrect syntax near ','.
Query execution failed for dataset 'Report'. (rsErrorExecutingCommand)
An error has occurred during report processing. (rsProcessingAborted)

The problem here is that the query is expecting a single string value, but the report is sending it an array of values when there are multiples selected.
In the parameter tab of your dataset properties, update the expression like this:
="," & Join(Parameters!ServerReport.Value, ",") & ","
This will combine the selected values into a single, comma-separated string.
Update your WHERE clause like this:
#ServerReport like '%,' + ServerInfo.Version + ',%'
This allows it to scan for the version string in the parameter string. The commas on the outside of both the joined parameter and the like statement prevent it from inadvertently matching partial strings.
Clarification:
This is all assuming that you actually need the like statement in the first place. Normally you would just say:
ServerInfo.Version IN (#ServerReport)
This would accept multiple values without any other changes. But the strings would have to be an exact match.

Related

Conditional update query to pad alphanumeric values in MS Access

I have an Access table with a field that contains alphanumeric values (1234, 123A, 12A34, ABC3, etc). I am trying to create a conditional update query to add leading zeros to bring all values that contain at least 1 letter up to five characters but none to the only numeric values (eg 123, 00A12, 0000X).
My current code looks like:
UPDATE MyTable SET MyTable!Field = Format(Field, String(5, "0")) WHERE MyTable!Field LIKE '*[A-Z]*'
When I run the query, I don't get any error messages but it also fails to add any leading zeros.
I've also tried Format(Field, "00000") using Not Like and '*[0-9]*' or '*[0123456789]*' etc.
Interestingly, when I run a query by itself to select any of the values containing a letter (Like '*[A-Z]*'), it correctly pulls all 1000 values that need to be updated but when I add the conditional, it fails. Similarly, I've been successful in the past with adding leading zeros the entire field using Format(Field), String(5, "0") but it also fails when I add a conditional.
I'm pretty new to Access and SQL, so I feel like I've probably misunderstood the syntax somewhere. Or is there something else I should be doing?
Format() is wrong function to use.
If every value in field is 5 characters or less, consider:
UPDATE MyTable SET Field = String(5-Len(Field), "0")) & Field WHERE Not IsNumeric(Nz(Field,0))

Why do I get different results depending on the function I use? (SQL Server)

I've been tasked with creating a report for my company. The report is generated from the results returned by the Stored Procedure spGenerateReport, which has multiple filters.
Inside the SP, this is how the filter is expected to work:
SELECT * FROM MyTable WHERE column1 IN (
'filters', 'for', 'this', 'report'
)
Entering the code above yields ~30000 rows in 9s. However, I want to be able to change my SP's filter by passing it a single argument (since I may use 1 or 2 or n filters), like so:
spGenerateReport 'Filters,for,this,report'
For this I have the User-Created Function fnSplitString (yes, I do know that there is a STRING_SPLIT function but I can't use it due to a lower compatibility level of my database) which splits a single string into a table, like so:
SELECT splitData FROM fnSplitString('Filters,for,this,report')
Returns:
splitData
------
Filters
for
this
report
Thus the final code in my SP is:
SELECT * FROM MyTable WHERE column1 IN (
SELECT * FROM fnSplitString('Filters,for,this,report')
)
However, this instead yields ~10000 rows in 60s. The time taken to complete this SP is weird but isn't too much of a problem, however nearly a quarter of my rows disappearing into the void certainly is. The results only have rows from the first couple filters (for example, 'Filters' and 'for'; if I change the order of the arguments (e.g.: fnSplitString('report,for,Filters,this')), I get a different number of rows, and only from filters 'report', 'for', 'Filters'! I don't understand why using the function returns different results than those obtained when using the literal strings. Is there some inside gimmick that I'm not aware of?
PS - I'm sorry in advance for being bad at explaining myself, and for any grammar mistakes
You should definitely be getting the same results with both techniques. Something is wrong.
You havent posted the fnSplitString code but I suspect fnSplitString is not outputting the last string in the list, or maybe the last string in the list is being truncated before it reaches fnSplitString so that no matches are found.
e.g. if the parameter going into your spGenerateReport stored procedure is varchar(20) then what will reach the function is 'Filters,for,this,rep' with the last bit truncated.
SSRS, for example, will truncate strings that are being passed into an SP instead of warning you with an error message

PowerQuery - Using a cell in a table as part of the code in a query (dynamically or not)

I am trying to use a cell as a parameter in Excel powerquery. The query works without this, but I have to manually input the values, which I need to constantly change them in the query in other to get the results that I want.
Query (Advanced Editor):
let
Criteria01 = Excel.CurrentWorkbook(){[Name="Servers"]}[Content][ServerSearch]{0},
Criteria02 = Excel.CurrentWorkbook(){[Name="Servers"]}[Content][ServerSearch]{1},
Criteria03 = Excel.CurrentWorkbook(){[Name="Servers"]}[Content][ServerSearch]{2},
Source = Sql.Database("SERVERNAMEHERE", "DATABASENAMEHERE", [Query="SELECT DISTINCT [...........] AND (TABLEPREF.COLUMNHERE like '%MANUALVALUE01%' OR#(lf)TABLEPREF.COLUMNHERE like '%MANUALVALUE02%' OR#(lf)TABLEPREF.COLUMNHERE like '%MANUALVALUE03%' OR#(lf)TABLEPREF.COLUMNHERE like Criteria01)#(lf)#(lf)#(lf)order by 1 asc"])
in
Source
"Servers" is the table name and "ServerSearch" is the column header. If I check the step for Criteria01/etc it will show me the correct value of that table that I need to use.
Original query done in Sql-Server. I have no problems when running the query with only LIKE '%MANUALVALUES%' lines.
My main goal is to automatically get N values of "MANUALVALUES" from a table in a sheet, which will be used as an input for comparing WHERE TABLEPREF.COLUMNHERE like '%VALUEHERE%'. I must use this and I can't get the whole table/database because there are way too many results besides the ones that I want.
However for test purposes at this moment, I am trying to use only 1-3 values, the first 3 of this table (Criteria{0}{1}{2} in the query above). However, if I try to do something like TABLEPREF.COLUMNHERE like Criteria01 I get the following error:
DataSource.Error: Microsoft SQL: Invalid column name 'Criteria01'.
Details:
DataSourceKind=SQL
DataSourcePath=dalsql390;itdw
Message=Invalid column name 'Criteria01'.
Number=207
Class=16
So my questions are:
I am getting the table cell value by the right way? Meaning:
Excel.CurrentWorkbook(){[Name="Servers"]}[Content][ServerSearch]{0}.
How do I refer this value in my query? Since the way that I wrote
that query bought me that error.
Also please note that if change TABLEPREF.COLUMNHERE like
Criteria01 to CHG1.CI_Name like "Criteria01" I get the
following error:
Expression.SyntaxError: Token Comma expected.
After fixed 1 and 2, how can I use this dynamically? For
example, instead of getting values of index 1 2 3, what if I want to
use a whole table? I know that using
Excel.CurrentWorkbook(){[Name="Servers"]}[Content] will bring me the whole table of values (1 column, unknown number of rows), but
how do I use this table content 1 by 1 in my query?
That will get the value, but you can't refer to steps inside of text values by putting the step name inside of it.
You have a couple options for doing this dynamically.
Use Value.NativeQuery to create a parameterized query where you can pass in other values as parameters. For example, Value.NativeQuery(Sql.Database("SERVERNAMEHERE", "DATABASENAMEHERE"), "select #a, #b", [a = 1, b = "x"]) will return the table [1, x]. You can put in the step name in the record value to pass that it (e.g. replace "x" with Criteria01).
Add the text values directly in the query field, e.g. [Query = "select " & Criteria01 ";"]. This is highly discouraged since this can lead to SQL injection issues.
For the third question, it depends what you want to do with the list of values. At some point you will likely need List.Accumulate to turn them all into a single text value which can be placed in the query value, and maybe to turn them into a record to place into the parameters value.

Trying to join Access tables with like statement with list in field

I have a problem that I have been hunting for a solution to, but to avail.
The basics are that I am trying to join 2 tables in Access by comparing a value in a field of Table 1 to a field in Table 2 that contains the number concatenated along with a few others in a list type format. (both fields are text type)
Example.
Table1.CWT value = 640242
Corresponding Table2.TAG_NO value I want to match to = 640242; 635894; 058426
So that it links the two tables based on the common value (640242 in this case).
So far, I have tried the following:
LEFT JOIN [Table2] ON [Table1].CWT like '*' & [Table2].TAG_NO & '*'
and
LEFT JOIN [Table2] ON [Table1].CWT & '*' like [Table2].TAG_NO
and what seems like every variation in between, I have even tried using % instead of *. But nothing works. In some cases, the value will be the second or third element in the string (635894 in above example), so I am looking for an option that will work in all cases. This is akin to looking for the equivalent of the CONTAINS function, but that does not seem to exist either.
Can anyone help me out?
Thanks
Ted
You need to switch the operands. And make sure that '640242' doesn't match '6402423', so add delimiters to both strings:
' ' & Table2.TAG_NO & ';' like '* ' & Table1.CWT & ';*'
You can use the Instr Function that tests if a string exists in other string as below:
Select [Table1].CWT, [Table1].OtherColumn, [Table2].Column1Needed,[Table2].Column2Needed
From [Table1], [Table2]
Where Instr([Table2].TAG_NO,[Table1].CWT)>0
See http://www.techonthenet.com/access/functions/string/instr.php

Using the Continuation character in a DEFINE statement in Oracle SQL Developer

I have the following code in which I'm using a variable to pass a list of values to multiple SQL statements (I can't save in a table as I don't have authority and don't want to have to maintain the list in all of the various SQL sections).
It works fine as long as all of the values are on a single line... but as I have so many values; I'd like to split it into multiple lines and use the Continuation Character '-'.
I'm running Oracle SQL Developer 2.1.1.64 against Oracle 10g (I also tried this in PL/SQL Developer and it failed there as well)
--=========================================
define subclasses = ('10-1010-10','10-1010-15','10-1010-20', -
'10-1010-25','10-1010-30') --- there are another 60 values...
select item from item_master where ((subclass) in &&subclasses);
Select Price from Item_prices where ((subclass) in &&subclasses);
--=========================================
I get the following error
ORA-01722: invalid number
01722. 00000 - "invalid number"
as it is parsing the code as
select item from item_master where ((subclass) in ('10-1010-10','10-1010-15',
'10-1010-20', -'10-1010-25','10-1010-30'))
...keeping the continuation code '-' in the SQL....tho it DOES go to the 2nd line of values.
If I remove the '-' ... it only processes the values on the first line and parses as
select item from item_master where ((subclass) in ('10-1010-10','10-1010-15','10-1010-20', )
... losing the second to nth line of values (and throwing errors as it ends w/ ',' and doesn't have the final ')'). How do I fix this?
You could do this:
column subc new_value subclasses
select q'[('10-1010-10','10-1010-15','10-1010-20',
'10-1010-25','10-1010-30')]' as subc
from dual;
Now &subclasses. will contain all the codes.
NB I used the q'[...]' quote syntax to avoid have to double up all the quotes in the data.
I noticed that you are trying to substitute a list of string variables into the select statement. You should rewrite your define statement to make it a single list of strings like this:
define subclasses = '''10-1010-10'',''10-1010-15'',''10-1010-20'', -
''10-1010-25'',''10-1010-30'''; --- there are another 60 values...
The - should be fine as a continuation character (see Oracle documentation here).
Now, when you execute your select statements you need to edit the WHERE clause so they are formatted so it will plug those values directly in there as written:
Select item from item_master where subclass in (&subclasses);
Select Price from Item_prices where subclass in (&subclasses);
This will end up being interpreted as if you had written:
Select item from item_master
where subclass in ('10-1010-10','10-1010-15','10-1010-20', '10-1010-25','10-1010-30');
If you have a lot of values though, you might run into limitations for substitution variables if you are using SQL*Plus (i.e. limited to 240 bytes per variable). In that case, you can either split the variables into multiple variables and concatenate them in the SELECT, or if you are in a PL/SQL environment, you can create variables that will hold the larger data size.