Friday, August 21, 2009

Passing an array to a stored procedure

Its very much often with the programmer that they need to pass an array or list as an argument or parameter in a stored procedure. I find this kind of scenario when the query consists of an 'IN' clause.
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 :

CREATE TABLE tbl_info
(
 

id varchar(2),
[name] varchar(100)





)


 




insert into tbl_info
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  lst_name and the member of the list are going to be used into the 'IN' clause of a query. So, create a string consisting of all members name in the list,
String param_string = "";

foreach(String s in lst_name)
{
  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

Rest Service using WEB API C#

This post will show a simple example of REST service built on Micrsoft WEB API framework. WEB API is an extensible framework from microsof...