Get dynamic SQL query statement return value (sp_executesql)

Source: Internet
Author: User

When writing stored procedures, you often encounter the need to splice SQL statements, generally only to perform the post-stitching statements using EXEC (@sql).

Today, a stored procedure needs to get the results of a dynamic SQL query.

Requirement Description: The cost value is queried in a table based on the ID value (table name is indeterminate but the table structure is determined, as in the following product table)

If we do not consider getting the return value, we can write this:

  Declare @tableName varchar( -)  Declare @id varchar(Ten)  Declare @costNumeric -,2)  Declare @sql nvarchar( $)    Set @tableName='Product'  Set @id='1'  Set @sql='Select cost from'+@tableName+'where id='+@id  exec(@sql)

The first attempt to get the return value is the following two methods:

Set @sql = '  '+@tableName+'  where id='+  @id-- Error Method 1  
Set @cost = (exec(@sql))    -- Error Method 2

Both of the above methods will be error, to help the almighty network to find a lovely function--sp_executesql can meet our requirements:

  Set @sql = '  '+@tableName+'  where [email protected]'   exec@sql, N'@cost Numeric (18,2) out, @id varchar  @cost out,@id

Not only can get the return value, but also can pass the parameter has no! Unfortunately, the table name still needs to be stitched into the SQL statement.

Note: The type of @sql needs to be one of the three types of ' Ntext/nchar/nvarchar '.

sp_executesql Introduction and use of the source of the garden friends in a more detailed introduction to this function.

Get dynamic SQL query statement return value (sp_executesql)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.