在SQL中从列创建varchar行

时间:2014-07-28 10:40:56

标签: sql sql-server

我有一个从表中返回列的函数。现在我想从我返回到单行的列中创建这些行。

CREATE PROCEDURE [dbo].[creareStringContract]
    @numeTabela varchar(100),
    @numeColoana varchar(100),
    @valoareColana varchar(50),
    @numeColoanaValori varchar(100)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @str varchar(max) = ''

    -- Add the T-SQL statements to compute the return value here
    exec ('SELECT ' +@numeColoanaValori +'
    FROM ' +  @numeTabela + '
    WHERE  ' + @numeColoana +' = ' + @valoareColana )

    -- Return the result of the function
END
GO

CREATE TABLE #tmp 
(
    ID int  IDENTITY (0,1),
    IDContract int,
    Valoare decimal 
)

    INSERT INTO #tmp VALUES (1,-500)
    INSERT INTO #tmp VALUES (1,300)
    INSERT INTO #tmp VALUES (1,250)
    INSERT INTO #tmp VALUES (1,150)
    INSERT INTO #tmp VALUES (1,50)
    INSERT INTO #tmp VALUES (2,-900)
    INSERT INTO #tmp VALUES (2,350)
    INSERT INTO #tmp VALUES (2,300)
    INSERT INTO #tmp VALUES (2,250)
    INSERT INTO #tmp VALUES (2,200)
    INSERT INTO #tmp VALUES (2,100)
    INSERT INTO #tmp VALUES (3,-600)
    INSERT INTO #tmp VALUES (3,280)
    INSERT INTO #tmp VALUES (3,270)
    INSERT INTO #tmp VALUES (3,160)
    INSERT INTO #tmp VALUES (3,150)
    INSERT INTO #tmp VALUES (4,-1500)
    INSERT INTO #tmp VALUES (4,500)
    INSERT INTO #tmp VALUES (4,400)
    INSERT INTO #tmp VALUES (4,300)
    INSERT INTO #tmp VALUES (4,250)
    INSERT INTO #tmp VALUES (4,150)
    INSERT INTO #tmp VALUES (4,100)
    INSERT INTO #tmp VALUES (4,50)
    INSERT INTO #tmp VALUES (4,30)
    INSERT INTO #tmp VALUES (1,10)
    INSERT INTO #tmp VALUES (1,5)
    INSERT INTO #tmp VALUES (1,4)
    INSERT INTO #tmp VALUES (1,3)
    INSERT INTO #tmp VALUES (1,2)

以下是样本数据。

exec [creareStringContract] '#tmp','IDContract','1','Valoare'

现在这个查询结果是。

Valoare
-500
300
250
150
50
10
5
4
3
2

现在我希望将其作为结果

IDContract  (No column name)
2              -500,300,250,150,50,10,5,4,3,2

1 个答案:

答案 0 :(得分:1)

在您的函数中使用以下查询:

EXEC('SELECT 2 IDContract, 
    STUFF((Select '',''+' +@numeColoanaValori +'
    FROM ' +  @numeTabela + '
    WHERE  ' + @numeColoana +' = ' + @valoareColana+'
    For XML Path('''')),1,1,'''') AS ''(No column name)''')