我有一个查询从表中返回合理数量的记录。我需要包含逗号分隔的字符串作为输出列。像这样的东西
SELECT
column1,
column2,
column3,
[Delimited string based on the id]
FROM
sometable
WHERE
id = someid
我知道你可以使用我过去使用过的coalesce函数但是我不确定如何将它集成到select语句中,还不能确定性能吗?
有什么想法吗?
答案 0 :(得分:0)
我遍历项目以构建字符串,然后将其添加到结果集中。
-- Minor performance tweak.
SET NOCOUNT ON
GO
-- ID of the item or widget or whatever
DECLARE @someid int
DECLARE @LookupItems TABLE
(
ID int IDENTITY (1, 1) PRIMARY KEY NOT NULL,
LookupTableID int, -- Primary key of the lookup table.
LookupField varchar(30) -- Text of the lookup value.
)
-- Update to the desired id.
SET @someid = 1234
INSERT INTO @LookupItems (ID, LookupField)
SELECT ID, Value
FROM dbo.somelookuptable
WHERE ID IN (
SELECT lookupid
FROM dbo.sometable
WHERE ID = @someid
)
DECLARE
@Count int,
@Max int,
@DelimitedString varchar(1000)
-- Initialize with a non-NULL value to facilitate concatenation.
SET @DelimitedString = ''
SET @Count = 1
SELECT @Max = MAX(ID) FROM @LookupItems
WHILE (@Count <= @Max)
BEGIN
SELECT @DelimitedString = @DelimitedString + IsNull(somefield, '') + ','
FROM @LookupItems
WHERE ID = @Count
SET @Count = @Count + 1
END
SELECT
column1,
column2,
column3,
@DelimitedString
FROM dbo.sometable
WHERE id = someid