SQL CSV作为查询结果列

时间:2017-01-10 22:53:13

标签: sql sql-server-2008

我有以下SQL查询单个表,单行,并将结果作为逗号分隔字符串返回,例如

Forms
1, 10, 4

SQL:

DECLARE @tmp varchar(250)
SET @tmp = ''
SELECT @tmp = @tmp + Form_Number + ', '
FROM  Facility_EI_Forms_Required
WHERE Facility_ID = 11 AND EI_Year=2012 -- single Facility, single year
SELECT SUBSTRING(@tmp, 1, LEN(@tmp) - 1) AS Forms

Facility_EI_Forms_Required表有三条Facility_ID = 11的记录

Facility_ID EI_Year Form_Number
11  2012    1
11  2012    10
11  2012    4

Form_number是一个varchar字段。

我有一个Facility表,其中包含Facility_ID和Facility_Name ++。

如何创建查询以查询给定年份的所有Facilites并生成CSV输出字段?

到目前为止,我有这个:

DECLARE @tmp varchar(250)
SET @tmp = ''
SELECT TOP 100 A.Facility_ID, A.Facility_Name,
    (
    SELECT @tmp = @tmp + B.Form_Number + ', '
    FROM  B
    WHERE B.Facility_ID = A.Facility_ID 
    AND B.EI_Year=2012
    )
FROM Facility A, Facility_EI_Forms_Required B

但是使用@tmp

会出现语法错误

我的猜测是这对于查询来说太复杂了,可能需要存储过程,但我对SP知之甚少。可以使用嵌套查询来完成吗?

我尝试了标量值函数

ALTER FUNCTION [dbo].[sp_func_EI_Form_List] 
(
    -- Add the parameters for the function here
    @p1 int,
    @pYr int
)
RETURNS varchar
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result varchar

    -- Add the T-SQL statements to compute the return value here
    DECLARE @tmp varchar(250)
    SET @tmp = ''
    SELECT @tmp = @tmp + Form_Number + ', '
    FROM OIS..Facility_EI_Forms_Required
    WHERE Facility_ID = @p1 AND EI_Year = @pYr -- single Facility, single year

    SELECT @Result = @tmp -- SUBSTRING(@tmp, 1, LEN(@tmp) - 1)-- @p1

    -- Return the result of the function
    RETURN @Result

END

电话

select Facility_ID, Facility.Facility_Name, 
   dbo.sp_func_EI_Form_List(Facility_ID,2012)
from facility where Facility_ID=11

返回

Facility_ID Facility_Name   Form_List
11  Hanson Aggregates   1

所以它只返回第一个记录而不是全部三个记录。我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试以下方法,这类似于回答Concatenate many rows into a single text string。我希望它是正确的,因为如果没有模式和一些演示数据我可以尝试一下(也许你可以在你的问题中添加模式和数据):

Select distinct A.Facility_ID, A.Facility_Name, 
    substring(
        (
            Select ',' + B.Form_Number AS [text()]
            From Facility_EI_Forms_Required B
            Where B.Facility_ID = A.Facility_ID 
            AND B.EI_Year=2012
            ORDER BY B.Facility_ID
            For XML PATH ('')
        ), 2, 1000) [Form_List]
From Facility A