Hi My Dear Friends,
Here i am going to explain how to show a comma seperated string to rows in SQL Server 2008.
Here i wrote a function for this as follows
alter FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX),@seperator varchar(1) )
RETURNS
@returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
WHILE CHARINDEX(@seperator, @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX(@seperator, @stringToSplit)
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)
INSERT INTO @returnList
SELECT @name
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
END
INSERT INTO @returnList
SELECT @stringToSplit
RETURN
END
ex 1: SELECT * FROM dbo.splitstring('91@12@65@78@56@789','@')
Gives the output as
Name
91
12
65
78
56
789
ex 2:
DECLARE @LIST VARCHAR(200)
SET @LIST = '2,4,3'
SELECT * FROM tbl WHERE recordid not IN (SELECT name FROM splitstring(@LIST,','))
Gives the output as
recordid
1
5
Here i am going to explain how to show a comma seperated string to rows in SQL Server 2008.
Here i wrote a function for this as follows
alter FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(MAX),@seperator varchar(1) )
RETURNS
@returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
WHILE CHARINDEX(@seperator, @stringToSplit) > 0
BEGIN
SELECT @pos = CHARINDEX(@seperator, @stringToSplit)
SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)
INSERT INTO @returnList
SELECT @name
SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
END
INSERT INTO @returnList
SELECT @stringToSplit
RETURN
END
ex 1: SELECT * FROM dbo.splitstring('91@12@65@78@56@789','@')
Gives the output as
Name
91
12
65
78
56
789
ex 2:
DECLARE @LIST VARCHAR(200)
SET @LIST = '2,4,3'
SELECT * FROM tbl WHERE recordid not IN (SELECT name FROM splitstring(@LIST,','))
Gives the output as
recordid
1
5
The above function is used for below versions of SQL Server 2016, why because SQL Server has introduced the new 'STRING_SPLIT' built in function in the version 2016.
Ex: SELECT * FROM STRING_SPLIT('a,b,c',',')Gives the output as Nameabc
x
Ex: SELECT * FROM STRING_SPLIT('a,b,c',',')Gives the output as Nameabc
x
No comments:
Post a Comment