我一直在尋找一種方法來顯示多行,一個單元格中的一列。它的內容用逗號分隔。顯示多行中的一列
例如,在代替:
專案編號標籤 ---- --- 1200 LABEL1 1200 LABEL2 1200 LABEL3
,我想我的查詢看起來是這樣的結果:
ProjectID Label
———— ——–
1200 label1, label2, label3
在此先感謝
我一直在尋找一種方法來顯示多行,一個單元格中的一列。它的內容用逗號分隔。顯示多行中的一列
例如,在代替:
專案編號標籤 ---- --- 1200 LABEL1 1200 LABEL2 1200 LABEL3
,我想我的查詢看起來是這樣的結果:
ProjectID Label
———— ——–
1200 label1, label2, label3
在此先感謝
有多種不同的方法可以做到這一點。一種選擇是創建一個表格值函數,它將不同記錄上的「多值」單元「分開」。下面是一個分割函數的例子:
ALTER FUNCTION [dbo].[Split](@RowData VARCHAR(MAX), @SplitOn VARCHAR(5))
RETURNS @RtnValue TABLE
(
Id int identity(1,1),
Data VARCHAR(MAX)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
創建後,您可以執行以下操作來獲得結果:
SELECT *
FROM YourTable A
CROSS APPLY dbo.Split(Label,', ') B
使用帶有分割函數的SQL Server表函數返回表
在查詢中需要幫助.... – user960439 2012-03-14 12:34:31
'PIVOT'完全沒有幫助 – Lamak 2012-03-14 12:35:00
在這裏,我已經表值函數其將字符串和返回如您所期望的結果
--Create the function
CREATE FUNCTION dbo.Split(@ProjectId nvarchar(50),@String varchar(8000), @Delimiter char(1)) --Pass projectID,label and delimiter and returns table
returns @temptable TABLE (id nvarchar(50),items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
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(id,Items) values(@ProjectId,@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
--Calling the function
select * from dbo.split('1200',' label1, label2, label3',',') --calling teh function
create table #comma_seprate
(ProductID int,
Lable varchar(max))
declare @index int, @id int;
declare @lable varchar(max);
declare cur_comma cursor
for select ProductID, Lable from comma_seprate
open cur_comma
fetch next from cur_comma into @id, @lable
while (@@fetch_status=0)
begin
set @index=charindex(',',@lable);
while(@index>0)
begin
insert into #comma_seprate values (@id,rtrim(ltrim(left(@lable,@index-1))));
set @lable=substring(@lable,@index+1,len(@lable));
set @index=charindex(',',@lable);
end
insert into #comma_seprate values (@id, rtrim(ltrim(@lable)));
fetch next from cur_comma into @id,@lable;
end
close cur_comma;
deallocate cur_comma;
select * from #comma_seprate;
truncate table #comma_seprate;
檢查這一項 http://stackoverflow.com/questions/5493510/turning-a-comma-separated-string-into-individual-rows – 2012-03-14 12:34:45