How to split a string into variables in sql?

前端 未结 3 981
抹茶落季
抹茶落季 2021-01-05 06:38

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,@

3条回答
  •  遥遥无期
    2021-01-05 07:04

    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''
    
    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.

提交回复
热议问题