我有一个表格tblexmaple,包含以下字段
FieldOne Field Two FieldThree
----------------------------------------------
1 Test1 1,2,3
2 Test2 2,3,4,5
3 Test3 1
结果想要是
1 Test1 1
1 Test1 2
1 Test1 3
2 Test2 2
2 Test2 3
2 Test2 4
2 Test2 5
3 Test3 1
任何人都可以帮忙吗?
答案 0 :(得分:0)
以下是您的问题解决方案。用你的tblexmaple替换Table_Test。并且在下面的查询中使用了函数,我也放了该函数的代码。
查询: -
DECLARE @Table TABLE
(
ID INT,
Name VARCHAR(100)
)
DECLARE @ResultTable TABLE
(
FieldOne INT,
FieldTwo VARCHAR(100),
FieldThree INT
)
INSERT INTO @Table
SELECT
ID,
Name
FROM Table_Test
DECLARE @ID INT;
DECLARE @Name VARCHAR(100);
DECLARE @IDs VARCHAR(100);
WHILE (SELECT COUNT(*) FROM @Table) > 0
BEGIN
SELECT TOP 1 @ID = ID,@Name = Name FROM @Table
SELECT @IDs = IDs FROM Table_Test WHERE ID = @ID
INSERT INTO @ResultTable
SELECT @ID, @Name, * FROM dbo.Split(@IDs,',')
DELETE FROM @Table WHERE ID = @ID
END
SELECT * FROM @ResultTable
Function Code :-
/****** Object: UserDefinedFunction [dbo].[Split] Script Date: 12/16/2013 12:15:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Split](@String varchar(MAX), @Delimiter char(1))
returns @temptable TABLE (items varchar(500))
as
begin
declare @idx int
declare @slice varchar(MAX)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
GO