简体   繁体   English

选择存储过程返回的列

[英]Select a column returned by a stored procedure

I have a stored procedure which is returning me about 50 columns. 我有一个存储过程,它返回我约50列。 I want to write a query, where I will be able to select a particular column from the list of column returned by the SP. 我想编写一个查询,在那里我将能够从SP返回的列列表中选择一个特定的列。

I tried writing select RSA_ID from exec(uspRisksEditSelect '1') But Its throwing me an error. 我尝试select RSA_ID from exec(uspRisksEditSelect '1')编写select RSA_ID from exec(uspRisksEditSelect '1')但它给我一个错误。 I think we need to write some dynamic sql for it. 我想我们需要为它编写一些动态的sql。 But I am new to it. 但我是新手。

You cannot use the results of a stored proc directly - you need to store that into an in-memory or temporary table and go from there: 您不能直接使用存储过程的结果 - 您需要将其存储到内存或临时表中并从那里开始:

DECLARE @tableVar TABLE (ID INT, Name VARCHAR(50))  -- whatever your sp returns

INSERT INTO @tableVar
    EXEC uspRisksEditSelect '1'

SELECT RSA_ID FROM @tableVar

But there's definitely no need to use dynamic SQL..... 但绝对没有必要使用动态SQL .....

您应该编写一个表值用户函数。

If you are able to modify your stored procedure, you can easily put number of needed columns as parameter: 如果您能够修改存储过程,则可以轻松地将所需列数作为参数:

CREATE PROCEDURE sp_GetDiffDataExample
      @columnsStatement NVARCHAR(MAX) -- Needed columns
AS
BEGIN
    DECLARE @query NVARCHAR(MAX)
    SET @query = N'SELECT ' + @columnsStatement + N' INTO ##TempTable FROM dbo.TestTable'
    EXEC sp_executeSql @query
    SELECT * FROM ##TempTable
    DROP TABLE ##TempTable
END

In this case you don't need to create temp table manually - it creates automatically. 在这种情况下,您无需手动创建临时表 - 它会自动创建。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM