sql-server - How to split a string from a table SQL Server 2012?
问题描述
I'd like to split comma-delimited strings in SQL Server 2012. I'm interested in an XML solution, not a function or while loop (performance and permissions reasons). I read this post: STRING_SPLIT in SQL Server 2012 which was helpful, however, my context is not splitting a variable but rather a column in a table. Below is an example of the kind of dataset I'm working with:
CREATE TABLE #EXAMPLE
(
ID INT,
LIST VARCHAR(1000)
)
INSERT INTO #EXAMPLE
VALUES (1, '12345,54321'), (2, '48965'), (3, '98765,45678,15935'), (4, '75315')
SELECT * FROM #EXAMPLE
DROP TABLE #EXAMPLE
Given that dataset, how could I go about splitting the LIST field on the comma so that I get this data set?
CREATE TABLE #EXAMPLE
(
ID INT,
LIST VARCHAR(1000)
)
INSERT INTO #EXAMPLE
VALUES (1, '12345'), (1, '54321'), (2, '48965'), (3, '98765'), (3, '45678'), (3, '15935'), (4, '75315')
SELECT * FROM #EXAMPLE
DROP TABLE #EXAMPLE
I feel like I'm blanking on implementing this with a table column as opposed to a variable, but I'm sure it's pretty similar. I'd be greatly appreciative of any input. Thanks!
解决方案
If you want an XML solution the following should hopefully suffice.
Note - this is easily wrapped in a reusable table-valued function however you state you don't want a function so just using in-line.
select e.id, s.List
from #example e
cross apply (
select List = y.i.value('(./text())[1]', 'varchar(max)')
from (
select x = convert(xml, '<i>' + replace(e.list, ',', '</i><i>') + '</i>').query('.')
) as a cross apply x.nodes('i') as y(i)
)s
See working Fiddle
推荐阅读
- c# - 查询 DbSet (C#) 时要求 Skip 和 Take
- r - 尝试安装软件包时 contrib.url(repos, "Source) 中的 R 错误,但未指定 repo
- sql - 当 SQL 中存在 NULL 连接值时,故意显示 NULL
- algorithm - Rust:从二进制字符串表示转换为 ASCII 字符串
- javascript - BigQuery 支持哪些 JS 语法?
- python - AttributeError:模块“grpc.experimental.aio”没有属性“StreamUnaryCall”-Google NLP API
- r - 通过折线图中的复选框显示多个输入(闪亮)
- match - Coq:Ltac 用于暗示的及物性(又名假设三段论)
- ruby - Ruby:在终端的输入行中添加符号?
- java - Wiremock:匹配字符串请求