mysql query parameter string array - mysql

I am trying to pass a parameter to a query, rather than write copious text I have narrowed it down to this simple explanation.
The frament I am trying to insert into is
where pkw_0.keyword in (:kwd)
I have used a String[] to construct a string of the form vals="'AVal','BVal'" which I pass to the query using setParameter("kwd",vals); The query returns zero results. However if I construct the query by hand and use the mysql console the query returns 1 result which is expected.
So I am assuming that either a single string is incorrect for the parameter or there is some conditioning of the values that I need to do prior to passing them via the setParameter call.

Each parameter can only represent a single literal value. You will need to create multiple placeholders in your prepared statement (one for each value) and then provide each value to MySQL as a separate parameter.

Related

MYSQL Best way to parametrize variable values for IN clause in stored procedure

I have to write a stored procedure where I want to set values for a variable called colorId using IN operator, the parameter can be a list of integer ids or no ids. I am wondering what should be the type of variable in the stored procedure?
where color_id IN (1,2,3,4);
Thanks for the help!
If you send a string like '1,2,3,4' as a single parameter, the query will run as if you had done this:
where color_id IN ('1,2,3,4');
The way MySQL does implicit type casts to integer, this converts the value to an integer using only the leading digits, and ignores everything after the first comma. So it will really run as if you had done this:
where color_id IN (1);
There is no way to "remove" the quotes. The point of query parameters is that they are not combined with the query until after the SQL parsing is done. Therefore the parameter is fixed as a single string value in that expression. You can't convert a parameter into a list of discrete values, because that would change the syntax of the query.
So you must pass multiple parameters, one for each value in your list. Like this:
...where color_id IN (?, ?, ?, ?);
And use some function in your client application to split the string into multiple parameters and then pass them not as a single string value, but as multiple integer values.
Some people try to use tricks like using MySQL's FIND_IN_SET() function, but I don't recommend this, because it cannot be optimized with any index.
You tagged this question stored-procedures from which I infer that you are trying to write a procedures that accepts a string of comma-separated integers and use it in an IN() predicate. This is more inconvenient to do in a stored procedure than in any other programming language, because MySQL's stored procedure language doesn't support arrays or good functions for splitting strings or counting elements. It can be done with enough effort, but the code is awful and you will quickly wish you were using any other language.
Your can pass parameter value like this - '1,2,3,4' and FIND_IN_SET function will be able to search in the provided string:
SELECT *
FROM colors
WHERE FIND_IN_SET(color_id, param); # param --> '1,2,3,4'

how to pass a database column as a parameter in a user defined function?

i have a code in sql for string comparison which takes two parameters as input works upon it and returns a result. both of the parameters are words, i want to change the parameter from a single word to a database column. how do i do that?
say for example in java its like storing the data in an array and than passing the whole array. can something like this be done in sql?
You can use the Select query for passing each value of a particular column from the table into your function.
like this,
SELECT compare_city_name('baroda',t.cityname) from tablename as t
In this query, you pass all cities name from cityname column to the function compare_city_name one by one.
Pass it as a VARCHAR, then build the query with "prepare" and "execute" it.

Script does not work when place the function inside the WHERE clause

I am trying to create a stored procedure, which receives a string and places it in the WHERE clause after processing it.
I created the function and when I call it from the body of a SQL statement, it returns the correct values:
('J1245',j3456','j1098')
However, when I call the function inside the WHERE clause as shown below, SQL does not show any records.
(Altcode in dbo.myfunction(#codes))
When I hard code it inside the WHERE clause, the SQL statement shows records.
(Altcode IN ('J1245',j3456','j1098'))
I suspect the function is returning a string (VARCHAR). If we reference the function anywhere in a SQL statement, the value returned by the function serves as a scalar value. The contents of the value don't change that. Any punctuation, single quotes, backticks, parens, commas, keywords, identifiers, et al. that happen to appear in the string are just part of the value.
The parser sees the return from the function simply as a single value, not as part of the SQL text.
It's not possible (in a single statement) to make the value returned by a function "become" part of the SQL text to be parsed.
As an example, in the WHERE clause, if we write:
WHERE altcode IN ( myfunc() )
The function myfunc is going to be evaluated, and the return will be single value, of a certain datatype, for example maybe a VARCHAR. Any parens or commas within the value are not interpreted as part of the SQL text. Those are just characters that are within the value.
It's as if we wrote SQL like this:
WHERE altcode IN ( ? )
And supplied a single value in place of the question mark placeholder. The SQL parser isn't seeing a list of values, it's not seeing any SQL to be executed. All the statement is seeing is a value.
It matters not one whit that we might supply a value that looks like SQL text, for example:
WHERE altcode IN ( '(SELECT code FROM all_altcodes)' )
That would be equivalent to writing
WHERE altcode = '(SELECT code FROM all_altcodes)'
And that is going to look for an exact match of altcode to the string literal.
Seems like there's a single quote missing in the value returned by the function, but maybe that's a typo in the question.
To get the string value returned by the function included as part of the SQL text, we would need to use dynamic SQL.
We would have to first call the function, and return the string. And then do some string concatenation to come up with another string that contains the SQL statement we want to execute, and then execute that string as a SQL statement.
So that would be two separate statement executions... one to get the function evaluated; and a second statement that is dynamically constructed, as a string, incorporating the value returned by the function.
(The question is tagged "MySQL", but I suspect this question is actually regarding SQL Server (given the reference to dbo. ?)
Preparing and executing dynamic SQL is similar in MySQL and SQL Server, but there are differences in the syntax.

IN() function with multiple parameter

Sample Data
When I am set parameter as in following way the not getting properly result.
Query:
SET #parmClientList ='7,11,14';
Select fkUserID from tbluserclient where MultipleClientID IN(#parmClientList);
but when I declare directly as hard coded then I getting proper result.
Query:
select fkUserID from tbluserclient where MultipleClientID IN(7,11,14);
Can some one suggest me how to pass multiple value to IN() function parameter.
The list in the IN() condition has to be a literal list, it won't split a string. Use FIND_IN_SET().
SELECT fkUserID FROM tbluserClient
WHERE FIND_IN_SET(CAST(MultipleClientID AS DECIMAL), #parmClientList);
Using CAST(MultipleClientID AS DECIMAL) performs the same conversion of that column from a comma-separated list to a single number that you get when you test it with IN(7,11,14). In both cases, it just checks whether the first number in the column is in the list.

Creating a concatenated string in SSRS with values enclosed in single quotes

I'm just starting developing reports in SSRS and would appreciate some help with this issue if possible! I'm selecting a dataset from a Dynamics database and want to then pass them to a SQL Server stored procedure referenced in another dataset to retrieve data from another database. I have created a report parameter and set it to Allow multiple values and to retrieve its values from a query and set it to the field that I want to retrieve.
The dataset would look like this:
U1234
U5678
U6789
In the dataset that uses the stored procedure I have set up a parameter, #pnum, and in the Parameter Value field I have created an expression using the Join statement like this:
Join(Parameters!pnum.Value, ", ")
When this gets passed to the stored proc it seems to be passing a string formatted like this:
'U1234, U5678, U6789'
Whereas what I would like to achieve is this:
'U1234', 'U5678', 'U6789'
so that I can use them in an IN statement. Is there a way of doing this within SSRS?
Many Thanks!
To anyone else experiencing this issue, the assumption made in the question on how the values are passed to the stored procedure and how they can be used are incorrect.
The value passed from the join expression would be formatted as such, without single quotes at the start and end:
U1234, U5678, U6789
Further to this, when passed to a stored procedure as a single string this can only be used as an in list by using dynamic SQL.
To parse out and filter on the passed values, the string will need to be split on the delimiter and inserted into a table (temporary or otherwise) to be joined to.
A suitable splitting can be found here (though others exist that may better suit your needs) utilising logic as follows:
declare #xml as xml,#str as varchar(100),#delimiter as varchar(10)
set #str='A,B,C,D,E'
set #delimiter =','
set #xml = cast(('<X>'+replace(#str,#delimiter ,'</X><X>')+'</X>') as xml)
select N.value('.', 'varchar(10)') as value from #xml.nodes('X') as T(N)
If you don't have to pass the values to a stored procedure and are using hardcoded datasets (Shared or not) you can actually directly use the parameter value without additional processing either in the query or by adding a join expression to the parameter value in the report:
select cols
from tables
where cols in(#MultiValueParameterName)
You have to add an extra field with the value wrapped in quotes.
Like this:
SELECT field1 AS display, '''' + field1 + '''' AS value