I have a string which looks like BAT | CAT | RAT | MAT I want to split this string into 4 parts and then store them into 4 different variables say .. @a,@b,@c,@d respectively.
How can it be done in sql?
I have a string which looks like BAT | CAT | RAT | MAT I want to split this string into 4 parts and then store them into 4 different variables say .. @a,@b,@c,@d respectively.
How can it be done in sql?
for splitting around a char :
DECLARE @A VARCHAR (100)= 'cat | bat | sat'
SELECT items
INTO #STRINGS
FROM dbo.split(@A,'|')
also see this link
DECLARE @test varchar(max);
set @test = 'Peter/Parker/Spiderman/Marvel';
set @test = Replace(@test, '/', '.');
SELECT ParseName(@test, 4) --returns Peter
SELECT ParseName(@test, 3) --returns Parker
SELECT ParseName(@test, 2) --returns Spiderman
SELECT ParseName(@test, 1) --returns Marvel
SQL Server 2005 : split string into array and get array(x)?
workarounds for splitting strings:
http://www.sqlperformance.com/2012/07/t-sql-queries/split-strings
sysname data type. Just do normal string shredding.ParseName because this seems to be very alluring piece of code to me.Nice and simple. (Using PATINDEX in Microsoft SQL Server Management Studio.)
DECLARE @string varchar(25) = 'BAT | CAT | RAT | MAT'
DECLARE @one varchar(5) = null
DECLARE @two varchar(5) = null
DECLARE @three varchar(5) = null
DECLARE @four varchar(5) = null
BEGIN
SET @one = SUBSTRING(@string, 0, PATINDEX('%|%', @string))
SET @string = SUBSTRING(@string, LEN(@one + '|') + 1, LEN(@string))
SET @two = SUBSTRING(@string, 0, PATINDEX('%|%', @string))
SET @string = SUBSTRING(@string, LEN(@two + '|') + 1, LEN(@string))
SET @three = SUBSTRING(@string, 0, PATINDEX('%|%', @string))
SET @string = SUBSTRING(@string, LEN(@three + '|') + 1, LEN(@string))
SET @four = @string
SELECT @one AS Part_One, @two AS Part_Two, @three AS Part_Three, @four AS Part_Four
END
You can split the values and insert them in a table variable, then assign them to your variables like this:
DECLARE @DataSource TABLE
(
[ID] TINYINT IDENTITY(1,1)
,[Value] NVARCHAR(128)
)
DECLARE @Value NVARCHAR(MAX) = 'BAT | CAT | RAT | MAT'
DECLARE @XML xml = N'<r><![CDATA[' + REPLACE(@Value, '|', ']]></r><r><![CDATA[') + ']]></r>'
INSERT INTO @DataSource ([Value])
SELECT RTRIM(LTRIM(T.c.value('.', 'NVARCHAR(128)')))
FROM @xml.nodes('//r') T(c)
SELECT [ID]
,[Value]
FROM @DataSource
The result if this query is:

Note, this technique is dynamic - it will split any count of strings split with | and store them in table variable table.