Sp_executesql [some insights on the stored procedures of SQL Server]

Source: Internet
Author: User
Sp_executesql
Execute statements or batch processing that can be reused multiple times or dynamically generated. Transact-SQL statements or batch processing can contain embedded parameters.
[For details, refer to SQL Server online help]

Here is a specific application. You can use this statement to obtain the content of a field from the table name with a variable. Previously, I used cursors. Example: declare @ tabn varchar (30), @ count int
Declare @ nsql nvarchar (1000) -- Note that the data type must be nvarchar.
Set @ tabn = 'authors '-- use the pubs Database
Set @ nsql = 'select @ COUNT = count (1) from' + @ tabn
Exec sp_executesql @ nsql, n' @ count int output', @ count output
Select @ count
In this way, the value of @ count can be obtained.
Implement with a cursor:
Declare @ tabn varchar (30), @ count int
Declare @ SQL varchar (1000)
Set @ tabn = 'authors '-- use the pubs Database
Set @ SQL = 'Clare cur_1 cursor for select count (1) from' + @ tabn
Exec (@ SQL)
Open cur_1
Fetch next from cur_1 into @ count
Close cur_1
Deallocate cur_1
Select @ count

Because the cursor consumes too much resources, use the cursor as little as possible.

Related Article

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.