Monday, October 6, 2008

String variable inside "IN" keyword of SQL

If you want to get all the records corresponding to the ID's, we can use a simple sql query with IN keyword.

Select * from Table_1 WHERE ID IN (1001,1002,1005,1006)

This query is simple as it looks. But when i want to replace the numbers with a string,
declare @pm varchar(100)
set @pm='1001,1002'
SELECT * FROM table2 WHERE groupid IN(@pm)

then it will raise an error "Conversion failed when converting the varchar value '1001,1002' to data type int."

To avoid this problem, we can change the all sql query to a string and execute it.
ie,

declare @pm varchar(100)
set @pm='1001,1002'

declare @pm1 varchar(100)
set @pm1='SELECT * FROM table2 WHERE groupid IN('
set @pm=@pm1 + @pm + ')'

exec(@pm)

I think this is the simple way!!!
Waiting for feedback.....

1 comment:

അപ്പൂപ്പന്‍താടി said...

I think in database driven applications
it would be better if we avoid passing coma separated values in a parameter in the design time itself.
Let it be exec,sp_execresultset,xp_execresultset.. whatever,
a compiled stored procedure will have a performance advantage for it doesnt have to parse and compile at runtime.
also in security point of view, it can be dangerous.