Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string into variables 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?

like image 989
SamuraiJack Avatar asked Dec 20 '13 07:12

SamuraiJack


3 Answers

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

like image 123
gaurav5430 Avatar answered Sep 23 '22 01:09

gaurav5430


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 
like image 33
Mat Avatar answered Sep 22 '22 01:09

Mat


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:

enter image description here

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

like image 45
gotqn Avatar answered Sep 22 '22 01:09

gotqn