我有一个字符串
('emp_id="123",emp_status="New Hire",emp_name="Smith, John A",emp_salary="2000",emp_state="VA"')
如何将其拆分为
Column Name Value
emp_id 123
emp_status New Hire
emp_name Smith, John A (Note: This has a comma within the string)
emp_salary 2000
emp_state VA
答案 0 :(得分:1)
解决此问题的一种方法是使用递归CTE。它可能不是最快的方式,但它是我在这种特殊情况下找到的最简单的方法:
DECLARE @Source varchar(200) = 'emp_id="123",emp_status="New Hire",emp_name="Smith, John A",emp_salary="2000",emp_state="VA"'
;WITH CTE AS
(
SELECT LEFT(@Source, CHARINDEX('",', @Source)) as val,
RIGHT(@Source, LEN(@Source) - CHARINDEX('",', @Source)-1) as string
UNION ALL
SELECT CASE WHEN CHARINDEX('",', string) > 0 THEN
LEFT(String, CHARINDEX('",', string))
ELSE
String
END as val,
CASE WHEN CHARINDEX('",', string) > 0 THEN
RIGHT(string, LEN(string) - CHARINDEX('",', string)-1)
ELSE
''
END as string
FROM CTE
WHERE LEN(string) > 0
)
SELECT LEFT(val, CHARINDEX('=', val)-1) As [Column Name],
REPLACE(RIGHT(val, LEN(val) - CHARINDEX('=', val) -1 ), '"', '') As Value
FROM CTE
结果:
Column Name Value
emp_id 123
emp_status New Hire
emp_name Smith, John A
emp_salary 2000
emp_state VA