博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
T-SQL Recipes之Separating elements
阅读量:4970 次
发布时间:2019-06-12

本文共 1639 字,大约阅读时间需要 5 分钟。

Separating elements

Separating elements is a classic T-SQL challenge. It involves a table called Arrays with strings holding comma-separated lists of values in a column called arr.

Run the following code to create the Arrays table, and populate it with sample data:

SET NOCOUNT ON;USE tempdb;IF OBJECT_ID(N'dbo.Arrays', N'U') IS NOT NULL    DROP TABLE dbo.Arrays;CREATE TABLE dbo.Arrays (      id  VARCHAR(10)    NOT NULL PRIMARY KEY    ,  arr VARCHAR(8000) NOT NULL    );GOINSERT INTO dbo.ArraysVALUES (    'A'    ,'20,223,2544,25567,14'    );INSERT INTO dbo.ArraysVALUES (    'B'    ,'30,-23433,28'    );INSERT INTO dbo.ArraysVALUES (    'C'    ,'12,10,8099,12,1200,13,12,14,10,9'    );INSERT INTO dbo.ArraysVALUES (    'D'    ,'-4,-6,-45678,-2'    );
View Code

The challenge, therefore, is to find an efficient set-based solution using T-SQL. To implement such a solution, you will want to split the task into three steps:

1. Generate copies.
2. Extract an element.
3. Calculate the position.

Generate copies

SELECT id    ,arr    ,nFROM dbo.Arrays     INNER JOIN AdventureWorks2014.dbo.Nums             ON n <= LEN(arr) AND SUBSTRING(N','+arr, n, 1) = ',';
View Code

This code generates the following output:

Extract an element

SUBSTRING(arr, n, CHARINDEX(',', arr + ',', n) – n).

Calculate the position

SELECT     id    ,ROW_NUMBER() OVER ( PARTITION BY id ORDER BY n) AS pos    ,SUBSTRING(arr, n, CHARINDEX(',', arr + ',', n) - n) AS elementFROM    dbo.Arrays      INNER JOIN AdventureWorks2014.dbo.Nums             ON n <= LEN(arr) + 1 AND SUBSTRING(',' + arr, n, 1) = ',';
View Code

转载于:https://www.cnblogs.com/cdjboy/p/5703986.html

你可能感兴趣的文章
iOS 加载图片选择imageNamed 方法还是 imageWithContentsOfFile?
查看>>
toad for oracle中文显示乱码
查看>>
SQL中Group By的使用
查看>>
错误org/aopalliance/intercept/MethodInterceptor解决方法
查看>>
两个表格中数据不用是一一对应关系--来筛选不同数据,或者相同数据
查看>>
hiho_offer收割18_题解报告_差第四题
查看>>
AngularJs表单验证
查看>>
静态方法是否属于线程安全
查看>>
02号团队-团队任务3:每日立会(2018-12-05)
查看>>
SQLite移植手记1
查看>>
js05-DOM对象二
查看>>
mariadb BINLOG_FORMAT = STATEMENT 异常
查看>>
C3P0 WARN: Establishing SSL connection without server's identity verification is not recommended
查看>>
iPhone在日本最牛,在中国输得最慘
查看>>
动态方法决议 和 消息转发
查看>>
C#生成随机数
查看>>
Java回顾之多线程
查看>>
机电行业如何进行信息化建设
查看>>
9、总线
查看>>
2018 Multi-University Training Contest 10 - Count
查看>>