Lets say we have a generic list of string which we need to pass in a stored procedure which i need to use into the 'IN' clause, then what should we do. Unfortunately, I did not found any built-in support for arrays in SQL Server's T-SQL.
To overcome this problem I found several alternatives but I am sharing here which seems to me the most easier one.
We can use a comma separated value straing to pass as an array. Here we are passing a single simple string but when it is executed it acts like an comma separated value in the query string.
The sample create table and stored procedure are as below :
(
[name] varchar(100)
)
select 'a1', 'rasel'
union all
select 'a2', 'rajib'
union all
select 'a3', 'Mujahid'
union all
select 'a4', 'Rokon'
union all
select 'a5', 'Sarwar'
union all
select 'a6', 'Reen'
CREATE PROC uspGetIdName@ListName varchar(100)
AS
BEGIN
DECLARE @SQL varchar(6000)
SET @SQL =
'SELECT * from tbl_info where [name] in (' + @ListName + ')'
EXEC(@SQL)
END
GO
For example in C#.net we are having a LIST
{
param_string = param_string + s;
}
Now pass the param_string into the stored procedure. If the lst_name consist of two names "rasel" and "rajib", then if we pass the param_string using the above procedure, the execute command will be similar to below :
EXEC uspGetIdName ' ''rasel'', ''rajib'' '
And you will get the desired result set.
As I said there are several other alternatives to overcome this problem, there are some limitaiton also to this technique. This is only possbile when we use dynamic query. But there are some drawback of using dynamic query generation and execution.
No comments:
Post a Comment