How to spilt data in sql server while using "IN" operator
Sometime you send multiple comma separated values as parameter to a stored procedure.
Suppose you are set the parameter value as below
param[0].value = "3,4,5,6";
The above set value doesn't work in stored procedure.
But as the column type is int then it query condition should be like column name in (3,4,5) and if you send the parameter as
It doesn't work in stored procedure, So i have used a function to split it and to use it.
USE [Database name] GO /****** Object: UserDefinedFunction [dbo].[Split_String] Script Date: 08/26/2011 11:12:59 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER FUNCTION [dbo].[Split_String](@Param_String varchar(2000),@Delmeter varchar(5)) RETURNS @RtnValue table ( Id int identity(1,1), Data nvarchar(100) ) AS BEGIN Declare @Cnt int Set @Cnt = 1 While (Charindex(@Delmeter,@Param_String)>0) Begin Insert Into @RtnValue (data) Select Data = ltrim(rtrim(Substring(@Param_String,1,Charindex(@Delmeter,@Param_String)-1))) Set @Param_String = Substring(@Param_String,Charindex(@Delmeter,@Param_String)+1,len(@Param_String)) Set @Cnt = @Cnt + 1 End Insert Into @RtnValue (data) Select Data = ltrim(rtrim(@Param_String)) Return END
Example:
SELECT NAME FROM TABLENAME WHERE FK_DEFAULT_ID IN (select data from [dbo].[Split_String] (@DEFAULTIDS,',') )
Note : @DEFAULTIDS is the parameter in stored procedure which contains value like "3,4,5,6" and type id varchar.
Nice
ReplyDelete