博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
T-SQL Recipes之Separating elements
阅读量:4972 次
发布时间: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

你可能感兴趣的文章
【ros】Create a ROS package:package dependencies报错
查看>>
通过容器编排和服务网格来改进Java微服务的可测性
查看>>
灰度图像和彩色图像
查看>>
argparse - 命令行选项与参数解析(转)
查看>>
修改上一篇文章的node.js代码,支持默认页及支持中文
查看>>
java只能的round,ceil,floor方法的使用
查看>>
将txt文件转化为json进行操作
查看>>
我的2014-相对奢侈的生活
查看>>
Java设计模式
查看>>
mysql-This version of MySQL doesn’t yet support ‘LIMIT & IN/ALL/ANY/SOME 错误解决
查看>>
基本概念复习
查看>>
红黑树
查看>>
【数据库】
查看>>
WindowManager.LayoutParams 详解
查看>>
安卓中数据库的搭建与使用
查看>>
.NET 设计规范--.NET约定、惯用法与模式-2.框架设计基础
查看>>
sql 内联,左联,右联,全联
查看>>
C++关于字符串的处理
查看>>
Breaking parallel loops in .NET C# using the Stop method z
查看>>
[轉]redis;mongodb;memcache三者的性能比較
查看>>