T10=] Charindex patindex

T-SQL Char index patindex

有没有人有脚本可以提取列中保存的数据以将服务器名称拆分到它们自己的列中?

| ID|  Servers
|:-:|---------------------------------------------------------------------------------
| 1 |   {"Name":"SQL-Vlfflk43E"}
| 2 |   {"Name":"SQL-VgflkglkdA"},{"Name":"SQL-VCkfkjgitrE"},{"Name":"SQL-;bv;b;b"},{"Name":"SQL-kkkbdddb"}
| 3 |  {"Name":"SQL-VgkgkgA"},{"Name":"SQL-VfkgkjygtbB"},{"Name":"SQL-lglg"}
| 4 |   {"Name":"SQL-VotoevB"},{"Name":"SQL-VCfkjfkjrtrE"},{"Name":"SQL-lglkgl"}
| 5 |   {"Name":"SQL-VblgltotA"},{"Name":"SQL-VCfkfkgE"},{"Name":"SQL-lkgkjgkg"}
| 6 |   {"Name":"SQL-VCggkgkg"}

所以ID 1 & 2会变成下面这样?我知道 char & patindex 可以帮助我努力解决这个问题。

| ID| Text                                                                                               | Server1       | Server2       | Server3   | Server4 
| 1 | {"Name":"SQL-Vlfflk43E"}                                                                           |SQL-Vlfflk43E  |null           |null       | null
| 2 | {"Name":"SQL-VgflkglkdA"},{"Name":"SQL-VCkfkjgitrE"},{"Name":"SQL-kkkbvb;b"},{"Name":"SQL-kkkbdddb"}|SQL-VgflkglkdA|SQL-VCkfkjgitrE|SQL-kkkbvb | SQL-kkkbdddb   

您可以将存储的数据转换为有效的 JSON 数组并用 JSON_VALUE():

解析它
SELECT 
   ID, 
   Server1 = JSON_VALUE(CONCAT('[', Servers, ']'), '$[0].Name'),
   Server2 = JSON_VALUE(CONCAT('[', Servers, ']'), '$[1].Name'),
   Server3 = JSON_VALUE(CONCAT('[', Servers, ']'), '$[2].Name'),
   Server4 = JSON_VALUE(CONCAT('[', Servers, ']'), '$[3].Name')
FROM (VALUES
   (1, '{"Name":"SQL-Vlfflk43E"}'),
   (2, '{"Name":"SQL-VgflkglkdA"},{"Name":"SQL-VCkfkjgitrE"},{"Name":"SQL-;bv;b;b"},{"Name":"SQL-kkkbdddb"}'),
   (3, '{"Name":"SQL-VgkgkgA"},{"Name":"SQL-VfkgkjygtbB"},{"Name":"SQL-lglg"}'),
   (4, '{"Name":"SQL-VotoevB"},{"Name":"SQL-VCfkjfkjrtrE"},{"Name":"SQL-lglkgl"}'),
   (5, '{"Name":"SQL-VblgltotA"},{"Name":"SQL-VCfkfkgE"},{"Name":"SQL-lkgkjgkg"}'),
   (6, '{"Name":"SQL-VCggkgkg"}')
) v (ID, Servers)

结果:

ID  Server1        Server2          Server3     Server4
-------------------------------------------------------------
1   SQL-Vlfflk43E           
2   SQL-VgflkglkdA SQL-VCkfkjgitrE  SQL-;bv;b;b SQL-kkkbdddb
3   SQL-VgkgkgA    SQL-VfkgkjygtbB  SQL-lglg    
4   SQL-VotoevB    SQL-VCfkjfkjrtrE SQL-lglkgl  
5   SQL-VblgltotA  SQL-VCfkfkgE     SQL-lkgkjgkg    
6   SQL-VCggkgkg