2011-08-05 22 views
0

我有一个查询从表中返回合理数量的记录。我需要包含逗号分隔的字符串作为输出列。事情是这样的如何在SQL Server 2000中创建逗号分隔的字符串?

SELECT 
column1, 
column2, 
column3, 
[Delimited string based on the id] 
FROM 
    sometable 
WHERE 
    id = someid 

我知道你可以使用聚结功能,我在过去已经使用但林不知道如何将它集成到一个select语句,也对性能真的不知道?

任何想法?

+0

您使用的是什么品种的SQL? MySQL,SQL服务器,Postgres? –

+0

这是什么RDBMS? SQL Server,MySQL? – Jacob

+0

@cularis道歉我不好。我使用SQLServer 2000 –

回答

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 
相关问题