Friday, March 27, 2009

Passing a Comma Delimited String Parameter to a Stored Procedure in SQL Server

When a comma delimited string is passed in a stored procedure as parameter, that cannot be used directly in query unless it is being parsed.
The below function parses the comma delimited string and extract each value,places it in a table and then can be used like a simple table.

User Defined Function :

SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[GET_STRING_IDS](@strIDs VARCHAR(8000))
RETURNS @TempTab TABLE
(
stringID VARCHAR(100)
)
AS
BEGIN
IF @strIDs IS NULL OR LEN(LTRIM(RTRIM(@strIDs))) = 0
RETURN

DECLARE
@strTemp VARCHAR(8000),
@intCurrCommaIndex INT,
@strInsertingID VARCHAR(100)
SELECT @strTemp = @strIDs

WHILE LEN(@strTemp) <> 0
BEGIN
SET @intCurrCommaIndex = CHARINDEX(',',@strTemp)
IF @intCurrCommaIndex > 0
BEGIN
SELECT @strInsertingID = SUBSTRING(@strTemp,1,@intCurrCommaIndex - 1)
SELECT @strTemp = SUBSTRING(@strTemp,@intCurrCommaIndex + 1,LEN(@strTemp) - @intCurrCommaIndex)
END
ELSE
BEGIN
SELECT @strInsertingID = @strTemp
SELECT @strTemp = ''
END
INSERT INTO @TempTab(stringID) VALUES(@strInsertingID)
END
RETURN
END


Callign the function from Stored Procedure :

CREATE PROCEDURE getEmpDetails
(
@strEmpIds VARCHAR(8000)=NULL
)
AS
BEGIN
IF(@strStatusIds IS NOT NULL )
BEGIN
SELECT * from tbl_Emp WHERE PK_EmpID IN(SELECT * FROM dbo.
GET_STRING_IDS(@strEmpIds))
END

END

No comments:

Post a Comment