简体   繁体   English

T-SQL将字符串拆分为多对一关系吗?

[英]T-SQL Split string into many-to-one relationship?

I have the following SQL script: 我有以下SQL脚本:

DECLARE @temp table (
    ID int IDENTITY(1, 1),
    data nvarchar(100)
)

INSERT INTO @temp (data) VALUES ('a,b,c')
INSERT INTO @temp (data) VALUES ('d,e,f')

SELECT *
FROM @temp AS T
    INNER JOIN
        (SELECT *
        FROM dbo.__StringSplit(T.data, ',', T.ID)) AS S
    ON T.ID = S.RefID

And on after clicking !Execute, I got these: 然后单击!Execute之后,我得到了这些:

Line 17 The multi-part identifier "T.data" could not be bound.

I have also tried the non-join version and got the same error: 我也尝试了非联合版本,并得到了相同的错误:

SELECT T.ID, S.Item AS dataItem
FROM @temp AS T, dbo.__StringSplit(T.data, ',', T.ID) AS S
WHERE T.ID = S.RefID

... ...

What I expected was that I should gets a table with IDs coming from @test.ID and each comma-separated values in @test.data gets split up into its own records and its value put into the dataItem field. 我所期望的是,我应该获得一个表,其ID来自@ test.ID,并且@ test.data中的每个逗号分隔值都拆分成自己的记录,并将其值放入dataItem字段中。

How can I accomplish that? 我该怎么做?
Am I required to use cursors? 我需要使用游标吗?

I've pasted the dbo.__StringSplit table-valued-function implementation at http://pastebin.com/f7dd6350f 我在http://pastebin.com/f7dd6350f粘贴了dbo .__ StringSplit表值函数实现

Thanks! 谢谢!

In SQL2000 you need cursors. 在SQL2000中,您需要游标。 In SQL2005/2008, you can use CROSS APPLY satement; 在SQL2005 / 2008中,可以使用CROSS APPLY填充。 probably like next (can't test just now): 可能像下一个(目前无法测试):

SELECT T.ID, S.Item AS dataItem
FROM @temp AS T CROSS APPLY dbo.__StringSplit(T.data, ',', T.ID) AS S

EDIT - I found this page on CROSS APPLY and then came up with: 编辑 -我在CROSS APPLY上找到了此页面 ,然后想到了:

SELECT T.ID, S.Item AS dataItem
FROM @temp AS T
    CROSS APPLY
    dbo.__StringSplit(T.data, ',', T.ID) AS S
WHERE T.ID = S.RefID

Which solved my problem :-) 解决了我的问题:-)

your split string function is really slow, here is a link to make a much faster one: 您的分割字符串函数确实很慢,这是一个使速度更快的链接:

http://www.sommarskog.se/arrays-in-sql.html http://www.sommarskog.se/arrays-in-sql.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM