简体   繁体   中英

How to write stored procedure passing select statement as input parameter?

I have a stored procedure that outputs a select statement as you see below:

select case when count(*) > 10 then ''A1'' else ''B1'' end as id, name, address from database.dbo.student

Now I want to write a stored procedure that takes such a select statement as string input, and return all the above outputs. I'm not sure where to assign the output variables.

ALTER PROCEDURE dbo.selectAttributes
    @select_statement Nvarchar(MAX),
    @id Nvarchar(255) OUT,
    @name nvarchar(255) OUT,
    @address nvarchar(255) OUT
AS 
BEGIN 
    DECLARE @query nvarchar(MAX)

    SET @query = @select_statement

    EXEC sp_executesql @query, 
                       N'@select_statement Nvarchar(MAX), 
                       @idOUT Nvarchar(255) OUTPUT,
                       @nameOUT nvarchar(255) OUTPUT,
                       @addressOUT nvarchar(255) OUTPUT',
                       @select_statement, @id OUTPUT, @name OUTPUT, @address OUTPUT
END

I think you are close:

ALTER PROCEDURE dbo.selectAttributes (
    @select_statement Nvarchar(MAX),
    @id Nvarchar(255) OUTPUT,
    @name nvarchar(255) OUTPUT,
    @address nvarchar(255) OUTPUT
) AS 
BEGIN 
    EXEC sp_executesql @select_statement,
         N'@id Nvarchar(255) OUTPUT, @name nvarchar(255) OUTPUT, @address nvarchar(255) OUTPUT',
           @id = @id OUTPUT,
           @name = @name OUTPUT,
           @address = @address OUTPUT
END;

In other words:

  • You have to put the OUTPUT keyword everywhere.
  • The query string does not go in as a parameter.
  • I don't rename the parameters, but if you do, they have to be declared somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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