gpt4 book ai didi

sql-server - 在 SQL Server 中从 CSV 列创建表,而不使用游标

转载 作者:行者123 更新时间:2023-12-02 10:53:10 26 4
gpt4 key购买 nike

给定一个表:

|Name    | Hobbies                |
-----------------------------------
|Joe | Eating,Running,Golf |
|Dafydd | Swimming,Coding,Gaming |

我想将这些行拆分出来以获得:

|Name    | Hobby     |
----------------------
|Joe | Eating |
|Joe | Running |
|Joe | Golf |
|Dafydd | Swimming |
|Dafydd | Coding |
|Dafydd | Gaming |

我已经完成了下面的操作(示例已准备好在 SSMS 中运行),购买我的解决方案使用我认为很难看的光标。有更好的方法吗?我正在使用 SQL Server 2008 R2,如果有任何新内容可以帮助我。

谢谢

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Split]') and xtype in (N'FN', N'IF', N'TF')) drop function [dbo].Split
go
CREATE FUNCTION dbo.Split (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)


go

declare @inputtable table (
name varchar(200) not null,
hobbies varchar(200) not null
)

declare @outputtable table (
name varchar(200) not null,
hobby varchar(200) not null
)

insert into @inputtable values('Joe', 'Eating,Running,Golf')
insert into @inputtable values('Dafydd', 'Swimming,Coding,Gaming')

select * from @inputtable

declare inputcursor cursor for
select name, hobbies
from @inputtable

open inputcursor

declare @name varchar(255), @hobbiescsv varchar(255)
fetch next from inputcursor into @name, @hobbiescsv
while(@@FETCH_STATUS <> -1) begin

insert into @outputtable
select @name, splithobbies.s
from dbo.split(',', @hobbiescsv) splithobbies

fetch next from inputcursor into @name, @hobbiescsv
end
close inputcursor
deallocate inputcursor

select * from @outputtable

最佳答案

使用像 here 那样的字符串解析函数。关键是用CROSS APPLY为基表中的每一行执行该函数。

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

declare @MyTable table (
Name char(10),
Hobbies varchar(100)
)

insert into @MyTable
(Name, Hobbies)
select 'Joe', 'Eating,Running,Golf'
union all
select 'Dafydd', 'Swimming,Coding,Gaming'

select t.Name, p.String
from @mytable t
cross apply dbo.fnParseStringTSQL(t.Hobbies, ',') p

DROP FUNCTION [dbo].[fnParseStringTSQL]

关于sql-server - 在 SQL Server 中从 CSV 列创建表,而不使用游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3660734/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com