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

后端 未结 4 536
一生所求
一生所求 2020-12-08 21:41

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 a

相关标签:
4条回答
  • 2020-12-08 22:28

    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 ║
    ╚══════════╩═══════════╩══════════╝  
    
    0 讨论(0)
  • 2020-12-08 22:34

    From SQL server 2016 onwards you can use this function string_split

    DECLARE @Var VARCHAR(4000);
    SET @Var =  '188,189,190,191,192,193,194'
    
    SELECT 1 as First_ID, value as Second_ID ,0 as Third_ID FROM string_split(@Var,',')
    
    0 讨论(0)
  • 2020-12-08 22:44

    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
    
    0 讨论(0)
  • 2020-12-08 22:44
    DECLARE @Table VARCHAR(100)='AAA,BBB,CCC,DDD'
    IF OBJECT_ID('[Comma_Split]') IS NOT NULL
    DROP TABLE [Comma_Split]
    CREATE TABLE [Comma_Split](ID INT IDENTITY(1,1),COL VARCHAR(100))
    while LEN(@Table)>0
    BEGIN
    DECLARE @COMMA INT= CHARINDEX(',', @Table)
    IF @COMMA=0 SET @COMMA=LEN(@Table)+1
    INSERT INTO [Comma_Split]
    SELECT SUBSTRING(@Table,1,@COMMA-1)
    SET @COMMA=@COMMA+1
    SET @Table=SUBSTRING(@Table,@COMMA,LEN(@Table))
    END
    
    0 讨论(0)
提交回复
热议问题