For eg :-
Select * from test table where some_words IN("some1","some2")
So in this query how can I write this in stored procedure where the values passed in IN()
parameter is user passed values.
In stored procedure-
Create definer Test(In user_input)
Begin
Select* from table where some_words IN(user_input);
End
Here the user_input will have only one value and I want it could accept comma separated multiple values how can I achieve this?
3
Answers
If you are using SQL Server, we can play with the adventure database. Inline table value functions are really important for optimization.
https://www.sqlshack.com/sql-server-inline-table-valued-function/
As for this, we can just get away with dynamic T-SQL if the list of input values is small.
This returns a result set of 350 rows.
This stored procedure takes a comma separated list for the in clause as a parameter. This can be enhanced by check if the @list is empty and changing the dynamic T-SQL. I will let you do that.
A sample call to the stored procedure is below.
The output is the same for both calls (select vs exec).
You can use prepared statements as follows :
This stored procedure takes comma separated list as parameter.
To call your SP use :
Demo here
The problem with prepared statements is that they lead to SQL Injection. This code has for parts: create table, insert data, check for valid list and return data given a list.
There are three calls to the stored procedure: sql injection, invalid list and valid list. Two out of the three do not return a result since our validation function tells the program not to execute the correct code. Please note, we are using the FIND_IN_SET() function, not the IN(). The later does not work correctly. Implicit casting is occurring with the PersonId.
Sample output from the last query.