t-sql是否有像oracle这样的可能性?: 我如何从表中获取一列并将其简洁地放入数组中? 如果不是ARRAY,则可能是逗号分隔的列表。...我的数据类型是字符串。
答案 0 :(得分:1)
这是如何执行逗号分隔值的另一个示例。将在SQL 2008 R2及更高版本中工作:
DECLARE @TestData TABLE
(
[ListItem] NVARCHAR(100)
);
--Declared as blank since leaving NULL will result in a final NULL value.
DECLARE @DelimitedString NVARCHAR(500) = '';
INSERT INTO @TestData (
[ListItem]
)
VALUES ( N'ListItem1' )
, ( N'ListItem2' )
, ( N'ListItem3' );
--puts the result set into @DelimitedString
SELECT @DelimitedString = @DelimitedString + [ListItem] + N','
FROM @TestData;
--Remove trailing comma
SET @DelimitedString = SUBSTRING(
@DelimitedString
, 1
, LEN(@DelimitedString) - 1
);
SELECT @DelimitedString;
答案 1 :(得分:0)
可以用光标强行使用它...
declare mycsv cursor for
select col1 from table1
declare @curItem nvarchar(max)
, @csvList nvarchar(255)
select @curItem = ''
, @csvList = ''
open mycsv
fetch next from mycsv into @curItem
while @@fetch_status = 0
begin
select @csvList = @csvList + @curItem + ','
fetch next from mycsv into @curItem
end
close mycsv
deallocate mycsv
select @csvList
...然后删去结尾的逗号。
希望我能想到更优雅的东西。
答案 2 :(得分:0)
我不确定您要查找的内容是什么,但是假设您想要用逗号分隔的客户ID(按客户姓氏)。像这样:
lastName, customerIDs
Smith 2,4,6,9,27
Jones 3,10,16,20
select lastname, (select cast(customerID as varchar(15))+',' from customers x where x.lastname=c.lastname for xml path('')) customerIDs
from customers c