March 20, 2011

SQL Server: Handle Delimited String passed as a Parameter to Stored Procedure

In your application, you may need to pass multiple values as a parameter to a stored procedure. This article shows how to pass delimited values to the procedure and get data

Consider this table:

Stored Proc Delimiter

Now if the id’s '1,4' are passed as a parameter, the records for these ids 1 and 4 should be returned. Create the following procedure

create procedure proc_testing
(
@id varchar(100)
)
as
select id,names from testing
where charindex(','+CAST(id as varchar(10))+',',','+@id+',')>0

go

In the stored procedure shown above, the WHERE condition checks if the value of id is found in the parameter string. The commas are added on both sides for accuracy.

Execute this procedure by passing ids, as shown below:

EXEC proc_testing '1,4'

The result includes records for the id’s 1 and 4

Stored Proc Delimiter

EXEC proc_testing '2,3,5'

The result includes records for the ids 2,3 and 5 as shown below

Stored Proc Delimiter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

1 comment:

Anonymous said...

How will this perform on a large table? I have a feeling it's not going to scale, but it's a good solution for a small data set.

Thanks for sharing it!