Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split comma delimited string and insert to a table (int)

Tags:

i have a table with 3 columns (First_ID,Second_ID,Third_ID) all columns are int columns.

Now I have 3 values, first and third values are int values (1 and 0), the second value is a comma delimited string ('188,189,190,191,192,193,194')

what should be my approach to populate the table like the bellow:

1   188 0
1   189 0
1   190 0
1   191 0
1   192 0
1   193 0
1   194 0

I have tried different ways but could not get it to work as i want.

Thanks in advance

like image 602
user3430556 Avatar asked May 03 '14 00:05

user3430556


People also ask

How can I split a string in a table in SQL?

The STRING_SPLIT(string, separator) function in SQL Server splits the string in the first argument by the separator in the second argument. To split a sentence into words, specify the sentence as the first argument of the STRING_SPLIT() function and ' ' as the second argument. FROM STRING_SPLIT( 'An example sentence.


2 Answers

Better use XML for this,

Declare @Var nvarchar(MAX)

Set @Var ='188,189,190,191,192,193,194'

DECLARE @XML AS XML

DECLARE @Delimiter AS CHAR(1) =','

SET @XML = CAST(('<X>'+REPLACE(@Var,@Delimiter ,'</X><X>')+'</X>') AS XML)

DECLARE @temp TABLE (ID INT)

INSERT INTO @temp

SELECT N.value('.', 'INT') AS ID FROM @XML.nodes('X') AS T(N)

SELECT * FROM @temp
like image 157
Jom George Avatar answered Oct 05 '22 08:10

Jom George


Using the Split() function you have mentioned in comments,

-- Variable holding comma separated values
DECLARE @Var VARCHAR(4000);
SET @Var =  '188,189,190,191,192,193,194'

-- Test Target Table
DECLARE @Target_Table TABLE  (First_ID INT,Second_ID INT,Third_ID INT) 

-- Insert statement
INSERT INTO @Target_Table
SELECT 1, CAST(Items AS INT) , 0 
FROM  dbo.Split(@Var, ',')  

-- Test Select
SELECT * FROM  @Target_Table  

Result Set

╔══════════╦═══════════╦══════════╗
║ First_ID ║ Second_ID ║ Third_ID ║
╠══════════╬═══════════╬══════════╣
║        1 ║       188 ║        0 ║
║        1 ║       189 ║        0 ║
║        1 ║       190 ║        0 ║
║        1 ║       191 ║        0 ║
║        1 ║       192 ║        0 ║
║        1 ║       193 ║        0 ║
║        1 ║       194 ║        0 ║
╚══════════╩═══════════╩══════════╝  
like image 35
M.Ali Avatar answered Oct 05 '22 08:10

M.Ali