Sunday, January 26, 2014

Sql - Comma separated string into table

CREATE TABLE tblEmployee(
EmployeeId          INT,
Name                VARCHAR(30),
Gender              VARCHAR(30),
City                VARCHAR(4000))
GO
DELETE FROM tblEmployee
GO
INSERT INTO tblEmployee(EmployeeId, Name, Gender, City) VALUES(1, 'Mark', 'Male', 'London')
GO
INSERT INTO tblEmployee(EmployeeId, Name, Gender, City) VALUES(2, 'John', 'Male', 'Chennai')
GO
INSERT INTO tblEmployee(EmployeeId, Name, Gender, City) VALUES(3, 'Mary', 'FeMale', 'New york')
GO
INSERT INTO tblEmployee(EmployeeId, Name, Gender, City) VALUES(4, 'Mike', 'Male', 'Sydney')
GO


Function:
------------
CREATE FUNCTION [dbo].[CsvToIntTable] ( @StringInput VARCHAR(8000) )
RETURNS @OutputTable TABLE ( [Id] int )
AS
BEGIN
    DECLARE @String    VARCHAR(20)
    WHILE LEN(@StringInput) > 0
    BEGIN
        SET @String      = LEFT(@StringInput, 
                                ISNULL(NULLIF(CHARINDEX(',', @StringInput) - 1, -1),
                                LEN(@StringInput)))
        SET @StringInput = SUBSTRING(@StringInput,
                                     ISNULL(NULLIF(CHARINDEX(',', @StringInput), 0),
                                     LEN(@StringInput)) + 1, LEN(@StringInput))
        INSERT INTO @OutputTable ( [Id] )
        VALUES ( cast(@String as int) )
    END
    
    RETURN
END


Declare @EmpId nvarchar(100);
Set @EmpId = '1,2'
Select * 
from dbo.tblEmployee
where EmployeeId IN (SELECT * FROM [dbo].[CsvToIntTable](@EmpId))

0 comments:

Post a Comment