Dynamic TSQL Gets the return value

Source: Internet
Author: User

Using execute and sp_executesql to implement dynamic TSQL, how to get the return value of dynamic TSQL?

Part I.: Execute

1,execute is a function that executes an SQL statement, and the example statement is as follows

Declare @sql nvarchar(Max)Declare @return_cnt intif object_id('tempdb: #tempcnt') is  not NULLDrop Table#tempcnt
Create Table#tempcnt (CNTint)Set @sql=N'INSERT INTO #tempcnt select COUNT (*) from sys.objects'exec(@sql)Select * from#tempcnt

As you can see from the sample code, the staging table is declared before the dynamic SQL scope, but it can be used in dynamic SQL, which indicates that the scope of the staging table is connection-oriented and that the temporary table can be accessed as long as the current link is present.

Part II: sp_executesql

1,sp_executesql has the ability to get the return value

Declare @sql nvarchar(Max)Declare @return_cnt intSet @sql=N'Select @cnt = count (*) from sys.objects'execsp_executesql@sqlN'@cnt int Output',@return_cntOutputPrint @return_cnt

Dynamic TSQL Gets the return value

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.