|
|
|
Have you ever come across the situaction when you have to pass mutiple values as parameter to your stored procedure.
Assume the following scenario.
- Your application pass comma seperated CustomerID list to stored procedure to get Orders for related customers.
Above requirement can be done in couple of ways. In this artical we will see 3 different approaches to perform this task.
Method-1 , Method-2 use UDF (User Defined Function) to Parse Array values and returns Table. Which can be used in where clause or JOIN.
Method-3 is to build dynamic SQL
Run the following script to test three different approaches |
Click here to copy the following block | Use Master Go
CREATE FUNCTION ParseArray (@Array varchar(8000), @separator char) RETURNS @ParsedArrays TABLE (row_counter int identity(1,1), array_value varchar(8000)) AS BEGIN declare @separator_position int declare @array_value varchar(8000) set @array = @array + @separator while patindex('%' + @separator + '%' , @array) <> 0 begin select @separator_position = patindex('%' + @separator + '%' , @array) select @array_value = left(@array, @separator_position - 1) insert @ParsedArrays(array_value) VALUES (@array_value) select @array = stuff(@array, 1, @separator_position, '') end RETURN END GO
Use Northwind Go Create proc usp_GetOrders @CustID_List varchar(500)='' As
Select o.* from Orders o Where CustomerID in(Select array_value from master.dbo.ParseArray(@CustID_List,',') as tmp)
Select o.* from Orders o JOIN master.dbo.ParseArray(@CustID_List,',') as tmp ON o.CustomerID =tmp.array_value
Declare @sql varchar(max) set @sql='Select o.* from Orders o Where CustomerID in(''' + replace(@CustID_List,',' , ''',''') + ''')' execute(@sql) go
exec usp_GetOrders 'ALFKI,VINET' |
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|