如何将列添加到存储过程结果?

时间:2017-09-18 09:21:07

标签: sql sql-server stored-procedures sql-server-2012

我有以下sql过程:

DECLARE @temp table
    (
       Column1 nvarchar(1000)
    )

    INSERT @temp (Column1)
    SELECT  fld_4
    FROM    MyTable
    WHERE   fld_1 = @param1 and
            fld_2 = @param2 and
            fld_3 = @param3

     SELECT ROW_NUMBER() OVER(ORDER BY Column1 ASC) AS Number, Split.a.value('.', 'VARCHAR(100)') AS Result
     FROM  
     (
         SELECT Column1,  
             CAST ('<M>' + REPLACE(Column1, ';', '</M><M>') + '</M>' AS XML) AS Result  
         FROM  @temp
     ) AS A CROSS APPLY Result.nodes ('/M') AS Split(a);

MyTable的结构:

| fld_1 | fld_2 | fld_3 | fld_4 | ... | fld_9 | ...|

fld_4包含这样的内容:

-9;-9;-1;-9;-9;-9;-9;-9;-1;-9;-9;-9;-9;-9;-9;-9;-9;-9;-1;-9;-9;-9;-9;-9;-9;-9;-9;-9;-1;-9;-1;-9;-9;-9;-1;-9;-9;-9;-9;-9;-9;-1;-1;-1;-1;-9;-1;-1;-9;-9;-9;-9;-1;-9;-1;-9;-9;-9;-1;-9;-1;-9;-1;-9;-9;-9;-9;-1;-9;-9;-1;-1;-9;-1;-1;0000;FFF8;-9;-9;-9;-1;-9;-1;-9;FFF6;-9;-1;-9;-1;-9;-1;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9;-9

我的程序返回一个具有以下结构的表:

| Number | Result |
|   1    |   -9   |
|   2    |   -9   |
|   3    |   -1   |
|  ...   |   ...  |

现在,我想实现以下结果:

| Number | Result |     NewColumn    |
|   1    |   -9   |  Value of fld_9  |
|   2    |   -9   |  Value of fld_9  |
|   3    |   -1   |  Value of fld_9  |
|  ...   |   ...  |  Value of fld_9  |

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

如果我理解您的要求,您只需要在结果集中包含其他列。像下面的代码片段应该工作。保留FROM子句,并在其末尾添加, MyTable

...
SELECT 
      ROW_NUMBER() OVER(ORDER BY Column1 ASC) AS Number
    , Split.a.value('.', 'VARCHAR(100)') AS Result
    , fld_9 AS NewColumn
FROM 
...
    , MyTable
WHERE
    MyTable.fld_1 = @param1 AND
    MyTable.fld_2 = @param2 AND
    MyTable.fld_3 = @param3;

答案 1 :(得分:0)

您无法直接调用Stored Procedure结果..

但是,您可以使viewtable-valued user-defined功能获得结果..

其他方式在TempTable

上插入存储过程结果
INSERT INTO #tempTable EXEC MyStoredProcedure

查看快速示例

Create PROCEDURE SampleStoreProc    
AS
BEGIN   
    Select 'Burak', 1 
END
GO


Create Table #TempTable
(    
    MyCol Varchar(50),
    ReferanceCol int
)

Insert into #TempTable Exec SampleStoreProc 

go

Create Table TestTable2 
(
    MyCol2 varchar(250),
    RefCol int
);

go

Insert into TestTable2 values ('Yeni', 1);

Select a.MyCol, b.MyCol2 From #TempTable a
left join TestTable2 b on b.RefCol = a.ReferanceCol