How to split a string in sql server 2008 using stored procedure and insert the data to table

后端 未结 3 1996
盖世英雄少女心
盖世英雄少女心 2021-01-15 08:13

I want to split a string in this format Quote:

\"date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8\"

. Actually this stri

3条回答
  •  我在风中等你
    2021-01-15 08:47

    In general, I'd suggest to write a CLR function which split strings by regex or SQL table-valued function, but in you case you can try something simple like converting your string to xml and parsing it:

    declare @str nvarchar(max) = 'date=10/10/2000|age=13^date=01/01/2001|age=12^date=02/02/2005|age=8'
    declare @data xml
    
    select @str = replace(@str, '=', '="')
    select @str = replace(@str, '|', '" ')
    select @str = replace(@str, '^', '"/>'
    
    select @data = cast(@str as xml)
    
    select
        t.c.value('@date', 'nvarchar(max)') as [date],
        t.c.value('@age', 'nvarchar(max)') as [age]
    from @data.nodes('row') as t(c)
    

    sql fiddle demo

提交回复
热议问题