求一sql函数写法
现有一个字符串str如下:
["A":12,"B":3,"C":1,"D":40]
怎样用一个函数把str的内容分解并依次赋值到下面的4个变量中
@p_A, @p_B, @p_C, @p_D int;
求精简的,谢谢!
[解决办法]
--仅供参考
DECLARE @str NVARCHAR(1000)
SET @str = '{["Aasd":12,"Bifg":3,"Csd":1,"Ddd":40],["Aasd":16,"Bifg":5,"Csd":0,"Ddd":49]}'
SET @str = REPLACE(SUBSTRING(@str,3,LEN(@str)-4), '"','')
SELECT
rowid,
fieldname = LEFT(c.NAME, CHARINDEX(':',c.name)-1),
fieldvalue = RIGHT(c.NAME,LEN(c.name)-CHARINDEX(':',c.name))
FROM
(
SELECT rowid = ROW_NUMBER() OVER(ORDER BY GETDATE()), name=CONVERT(XML, '<root><v>'+replace(b.name,',','</v><v>')+'</v></root>') FROM
(SELECT [name]=CONVERT(XML, '<root><v>'+replace(@str,'],[','</v><v>')+'</v></root>')) a
OUTER APPLY
(SELECT [name] = C.v.value('.','NVARCHAR(MAX)') FROM a.[name].nodes('/root/v') C(v)) b
) t
CROSS APPLY
(
SELECT [name] = C.v.value('.','NVARCHAR(MAX)') FROM t.[name].nodes('/root/v') C(v)
) c
/*
rowidfieldnamefieldvalue
1Aasd12
1Bifg3
1Csd1
1Ddd40
2Aasd16
2Bifg5
2Csd0
2Ddd49
*/