How to split a string into variables in sql?

前端 未结 3 962
抹茶落季
抹茶落季 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 06:59

    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 
    

提交回复
热议问题