SQL Server 2008 从记录中的字段拆分字符串

2022-11-14数据库问题
18

本文介绍了SQL Server 2008 从记录中的字段拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个如下所示的数据集(输入).

I have a data set that looks like the below (the input).

IR#   CR#
1     1,2
2     3
3     4,5,6

我想要以下输出.对于本示例,您可以考虑所有字段 varchar.

I would like the following output. You can consider all fields varchar for this example.

IR#   CR#
1     1
1     2
2     3
3     4
3     5
3     6

我有 UDF 将 CSV 字符串拆分为行...但不能将表中的 1 行拆分为多行,然后联合将下一行等.

I have UDFs to split a CSV string into rows...but not something to split 1 row in a table into multiple rows and then union will the next row, etc.

谢谢!

推荐答案

使用 CROSSAPPLY 与您的拆分 UDF 结合使用.我在示例中使用的字符串拆分器来自 此处.

Use CROSS APPLY in conjunction with your splitting UDF. The string splitter I'm using for my example comes from here.

/* Create function for purposes of demo */
CREATE FUNCTION [dbo].[fnParseStringTSQL] (@string NVARCHAR(MAX),@separator NCHAR(1))
RETURNS @parsedString TABLE (string NVARCHAR(MAX))
AS 
BEGIN
   DECLARE @position int
   SET @position = 1
   SET @string = @string + @separator
   WHILE charindex(@separator,@string,@position) <> 0
      BEGIN
         INSERT into @parsedString
         SELECT substring(@string, @position, charindex(@separator,@string,@position) - @position)
         SET @position = charindex(@separator,@string,@position) + 1
      END
     RETURN
END
go

/* Set up sample data */
declare @t table (
    IR int,
    CR varchar(100)
)

insert into @t
    (IR, CR)
    select 1, '1,2' union all
    select 2, '3' union all
    select 3, '4,5,6'

/* Here's the query that solves the problem */
select t.IR, p.string
    from @t t
        cross apply [dbo].[fnParseStringTSQL](t.CR,',') p


/* clean up after demo */
drop function [dbo].[fnParseStringTSQL]

这篇关于SQL Server 2008 从记录中的字段拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End
SQLServer

相关推荐

将可变参数列表传递给 SqlServer2008 存储过程的理智/快速方法
Sane/fast method to pass variable parameter lists to SqlServer2008 stored procedure(将可变参数列表传递给 SqlServer2008 存储过程的理智/快速方法)...
2023-10-26 数据库问题
1

为什么SqlServer select语句会选择匹配的行和匹配并带有尾随空格的行
Why would SqlServer select statement select rows which match and rows which match and have trailing spaces(为什么SqlServer select语句会选择匹配的行和匹配并带有尾随空格的行)...
2023-10-08 数据库问题
3

SQLSERVER 中的 ListAGG
ListAGG in SQLSERVER(SQLSERVER 中的 ListAGG)...
2023-07-18 数据库问题
7

相当于 mySQL 中的 SQLServer 函数 SCOPE_IDENTITY()?
The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?(相当于 mySQL 中的 SQLServer 函数 SCOPE_IDENTITY()?)...
2023-04-28 数据库问题
59

使用 spark sql 在 sqlserver 上执行查询
execute query on sqlserver using spark sql(使用 spark sql 在 sqlserver 上执行查询)...
2023-04-04 数据库问题
8

Debezium 如何使用 Kafka Connect 正确注册 SqlServer 连接器 - 连接被拒绝
Debezium How do I correctly register the SqlServer connector with Kafka Connect - connection refused(Debezium 如何使用 Kafka Connect 正确注册 SqlServer 连接器 - 连接被拒绝)...
2023-04-03 数据库问题
3