SQL Server string to table function - sql-server

Does someone have a good, fast SQL Server function that will take a string with a delimiter and return it as a table?
Thanks

CREATE FUNCTION dbo.fnSplit(
#sInputList VARCHAR(8000) -- List of delimited items
, #sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS #List TABLE (item VARCHAR(8000))
BEGIN
DECLARE #sItem VARCHAR(8000)
WHILE CHARINDEX(#sDelimiter,#sInputList,0) <> 0
BEGIN
SELECT
#sItem=RTRIM(LTRIM(SUBSTRING(#sInputList,1,CHARINDEX(#sDelimiter,#sInputList,0)-1))),
#sInputList=RTRIM(LTRIM(SUBSTRING(#sInputList,CHARINDEX(#sDelimiter,#sInputList,0)+LEN(#sDelimiter),LEN(#sInputList))))
IF LEN(#sItem) > 0
INSERT INTO #List SELECT #sItem
END
IF LEN(#sInputList) > 0
INSERT INTO #List SELECT #sInputList -- Put the last item in
RETURN
END
GO
--Test
select * from fnSplit('1,22,333,444,,5555,666', ',')
select * from fnSplit('1##22#333##444','##') --note second item has embedded #
select * from fnSplit('1 22 333 444 5555 666', ' ')

Added a bit of a twist to get the resulting items to be Integers and leveraged the NVARCHAR(MAX) capabilities of SQL 2008+
GO
/****** Object: UserDefinedFunction [dbo].[udf_fnSplit] Script Date: 05/28/2013 15:22:00 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_fnSplit](
#sInputList VARCHAR(MAX) -- List of delimited items
, #sDelimiter VARCHAR(MAX) = ',' -- delimiter that separates items
) RETURNS #List TABLE (id int)
BEGIN
DECLARE #sItem VARCHAR(8000)
WHILE CHARINDEX(#sDelimiter,#sInputList,0) <> 0
BEGIN
SELECT
#sItem=RTRIM(LTRIM(SUBSTRING(#sInputList,1,CHARINDEX(#sDelimiter,#sInputList,0)-1))),
#sInputList=RTRIM(LTRIM(SUBSTRING(#sInputList,CHARINDEX(#sDelimiter,#sInputList,0)+LEN(#sDelimiter),LEN(#sInputList))))
IF LEN(#sItem) > 0
INSERT INTO #List SELECT CONVERT(INT,#sItem)
END
IF LEN(#sInputList) > 0
INSERT INTO #List SELECT #sInputList -- Put the last item in
RETURN
END

Related

Remove the Elements which in another string

I have a column Airports where it has values as 'DXB,KWI,COK'.
I need to compare these column value with a string like 'DXB,LHR' remove the column value which in comma separated string?
After checking with string I want to update the column value as 'KWI,COK'.?
Any solutions
Airports |id
_____________________
dxb,cok,kwi |1
cok,dxb |2
kwi,dxb |3
Airport column id 1 will to update as 'COK,DXB' remove dxb which is in compared comma separated value?
Try to use REPLACE function:
CREATE TABLE #Test(
Airports varchar(256),
id int
)
INSERT #Test(Airports,id)VALUES('dxb,cok,kwi',1)
INSERT #Test(Airports,id)VALUES('cok,dxb',2)
INSERT #Test(Airports,id)VALUES('kwi,dxb',3)
INSERT #Test(Airports,id)VALUES('kwi,dxb,zxc',4)
INSERT #Test(Airports,id)VALUES('dxb',5)
INSERT #Test(Airports,id)VALUES('aaa,bbb',6)
SELECT *,REPLACE(REPLACE(REPLACE(Airports,'dxb,',''),',dxb',''),'dxb','')
FROM #Test
UPDATE #Test
SET
Airports=REPLACE(REPLACE(REPLACE(Airports,'dxb,',''),',dxb',''),'dxb','')
WHERE Airports LIKE '%dxb%'
SELECT *
FROM #Test
DROP TABLE #Test
ALTER FUNCTION [dbo].[SplitString]
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
ALTER FUNCTION [dbo].[DistinctSplitString]
(
#string1 nvarchar(max),
#string2 nvarchar(max),
#chars character(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
INSERT INTO #output
select SP1.Item from dbo.SplitString(#string1,#chars) as SP1
LEFT JOIN dbo.SplitString(#string2,#chars) as SP2
ON SP1.Item = SP2.Item
WHERE sp2.Item IS NULL
RETURN
END
By using this two function we can easily get values

exec statement in sql for comma separated values

I have created a SP like below. where i will have to pass comma separated values to #ID parameter.I have given split function. It is working fine only if i give one value as ID. Kindly help how should i change the exec statement for the SP to give comma separated values like ('123',456) to SP
EXEC usp_2090_AppRej '54862','',''
ALTER PROCEDURE [dbo].[usp_2090_AppRej]
#ID VARCHAR(100)
,#Comments VARCHAR(1000) = ''
,#ReturnMessage VARCHAR(500) OUTPUT
DECLARE #tblBPM TABLE (ids INT)
INSERT INTO #tblBPM
SELECT items
FROM dbo.Split(#ID, ',')
You are using SQL server try the following.
Create database function
ALTER FUNCTION [dbo].[fnSplit]
(
#sInputList VARCHAR(max) -- List of delimited items
,
#sDelimiter VARCHAR(max) = ',' -- delimiter that separates items
)
RETURNS #List TABLE ( item VARCHAR(max) )
BEGIN
DECLARE #sItem VARCHAR(max)
WHILE CHARINDEX(#sDelimiter, #sInputList, 0) <> 0
BEGIN
SELECT #sItem = RTRIM(LTRIM(SUBSTRING(#sInputList, 1,
CHARINDEX(#sDelimiter,
#sInputList, 0)
- 1))) ,
#sInputList = RTRIM(LTRIM(SUBSTRING(#sInputList,
CHARINDEX(#sDelimiter,
#sInputList, 0)
+ LEN(#sDelimiter),
LEN(#sInputList))))
IF LEN(#sItem) > 0
INSERT INTO #List
SELECT #sItem
END
IF LEN(#sInputList) > 0
INSERT INTO #List
SELECT #sInputList -- Put the last item in
RETURN
END
Create SP
CREATE PROCEDURE [dbo].[usp_2090_AppRej]
#ID VARCHAR(100),
#Comments VARCHAR(1000) = '',
#ReturnMessage VARCHAR(500) OUTPUT
AS
BEGIN
DECLARE #tblBPM TABLE ( ids INT )
INSERT INTO #tblBPM
SELECT item
FROM dbo.fnSplit(#ID, ',')
END

insert collection of data into sql server columns with storedprocedure

i'm begginer in sql server
i want to insert collection of data into the column in stored procedure
i want pass data from c# like this (100,'3,5,4,2,9') and insert to the column like this
ID Number
100 3
100 5
100 4
100 2
100 9
My procedure code
ALTER PROCEDURE [dbo].[Number]
#Number CHAR(10),
AS
BEGIN
BEGIN TRY
INSERT INTO NumbersTbl
VALUES(#Number)
SELECT 1
END TRY
BEGIN CATCH
EXEC SQLError
SELECT -1
END CATCH
END
how i can do it?
thank you
Procedure Definition
ALTER PROCEDURE [dbo].[Number]
#Value INT,
#Number Varchar(100),
#Sucecc BIT OUTPUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #xml xml;
BEGIN TRY
SET #xml = cast(('<X>'+replace(#Number,',' ,'</X><X>')+'</X>') as xml)
INSERT INTO NumbersTbl (Column1 , Column2)
SELECT #Value, N.value('.', 'varchar(100)') as value
FROM #xml.nodes('X') as T(N)
SET #Sucecc = 1;
END TRY
BEGIN CATCH
EXEC SQLError
SET #Sucecc = 0;
END CATCH
END
Call Procedure
DECLARE #Result BIT;
Exec [dbo].[Number] #Value = 100
,#Number = '3,5,4,2,9'
,#Sucecc = #Result OUTPUT
First you can create the special function to parse input numbers:
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS
#returnList TABLE ([Numbers] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #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
And then edit your procedure:
ALTER PROCEDURE [dbo].[Number]
#ID INT,
#Number VARCHAR(MAX)
AS
BEGIN
BEGIN TRY
INSERT INTO NumbersTbl(ID, Number)
SELECT #ID, Numbers
FROM dbo.splitstring(#Number)
END TRY
BEGIN CATCH
EXEC SQLError
SELECT -1
END CATCH
END
Call: EXEC Number 100,'3,5,4,2,9'

How to insert a comma separated values to the column to a SQL table in a order same as passing order?

i written a code like below to insert a comma separated values to the tempTble.It is working but i need the values to be entered in a order same as am passing it to query.But here number are arranged in a numerical order and string values arranged according to alphabetical order .Example '7,6,5,1,2,Jack,Ana,Micky' but it is inserted to column in a order of '1,2,5,6,7,Ana,Jack,Micky'.
Can you please provide answer for this.
Thank you in advance
ALTER PROCEDURE [dbo].[usp_GetValuesFromBillingSystem]
(
#BillingSystemCode VARCHAR(max)
)
AS
BEGIN
DECLARE #planID varchar(max) = Null ;
SET #planID= #BillingSystemCode
DECLARE #tempTble Table (planID varchar(50) NULL);
while len(#planID ) > 0
begin
insert into #tempTble (planID ) values(left(#planID , charindex(',', #planID +',')-1))
set #planID = stuff(#planID , 1, charindex(',', #planID +','), '')
end
select * from #tempTble
END
www.aspdotnet-suresh.com/2013/07/sql-server-split-function-example-in.html
CREATE FUNCTION dbo.Split(#String nvarchar(4000), #Delimiter char(1))
RETURNS #Results TABLE (Items nvarchar(4000))
AS
BEGIN
DECLARE #INDEX INT
DECLARE #SLICE nvarchar(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
-- ERO FIRST TIME IN LOOP
SELECT #INDEX = 1
WHILE #INDEX !=0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT #INDEX = CHARINDEX(#Delimiter,#STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF #INDEX !=0
SELECT #SLICE = LEFT(#STRING,#INDEX - 1)
ELSE
SELECT #SLICE = #STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO #Results(Items) VALUES(#SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT #STRING = RIGHT(#STRING,LEN(#STRING) - #INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(#STRING) = 0 BREAK
END
RETURN
END

A way to split in sqlserver

Is there a way to split in sql server nvarchar looking like this:
'some text[tag1][tag2] [tag3]'
into:
[tag1]
[tag2]
[tag3]
?
p.s.
I've update example data to show, that there's no strict separator. I need to get everything inside brackets!
Try below.
declare #v varchar(1000)
set #v = '[1212][12121212] [[['
create table #temp
(
v varchar(1000)
)
--insert into #temp(v)values(#v)
declare #Firstindex int
declare #Secondindex int
declare #subval varchar(100)
Set #Firstindex = charindex('[', #v, 1)
while(#Firstindex <> 0)
Begin
Set #Firstindex = charindex('[', #v, #Firstindex)
if(#Firstindex = 0)
break
Set #Secondindex = charindex(']', #v, #Firstindex)
if(#Secondindex = 0)
break;
if(#Firstindex + 1 <> #Secondindex)
Begin
set #subval = substring(#v, #Firstindex + 1, (#Secondindex - 1) - (#Firstindex ))
select #subval
Insert into #temp values(#subval)
End
set #Firstindex = #Secondindex
End
select * from #temp
drop table #temp
You can use the following function
CREATE FUNCTION [dbo].[fnSplit](
#sInputList VARCHAR(8000)
, #sDelimiter VARCHAR(8000) = ','
) RETURNS #List TABLE (ID VARCHAR(8000))
BEGIN
DECLARE #sItem VARCHAR(8000)
WHILE CHARINDEX(#sDelimiter,#sInputList,0) <> 0
BEGIN
SELECT
#sItem=RTRIM(LTRIM(SUBSTRING(#sInputList,1,CHARINDEX(#sDelimiter,#sInputList,0)-1))),
#sInputList=RTRIM(LTRIM(SUBSTRING(#sInputList,CHARINDEX(#sDelimiter,#sInputList,0)+LEN(#sDelimiter),LEN(#sInputList))))
IF LEN(#sItem) > 0
INSERT INTO #List SELECT #sItem
END
IF LEN(#sInputList) > 0
INSERT INTO #List SELECT #sInputList
RETURN
END
The output can be verified like
select * from dbo.fnSplit('[12] [12] [13]',' ')
It will show
12
12
13

Resources