T-SQL Recipes Table Variables and temporary Tables and CTE

Source: Internet
Author: User

Problem many times, we want table variables to execute in dynamic SQL, but the reality is very bony. such as this example:
DECLARE @sql_command NVARCHAR(MAX);DECLARE @parameter_list NVARCHAR(MAX);DECLARE @last_names TABLE(last_nameNVARCHAR( -) );SELECT  @sql_command = 'Select Distinctfirstnamefrom person.personwhere LastName in (select Last_Name from @last_names)'EXECsp_executesql@sql_command;
View Code
Some people see here, perhaps the first instinct will ask, why not in dynamic SQL declaration @last_names, in fact, and eggs.
This road is not going to work, let's change the way, for example, type Table:
CREATETYPE last_name_table as TABLE(last_nameNVARCHAR( -));GO--DROP TYPE last_name_tableDECLARE @sql_command NVARCHAR(MAX);DECLARE @parameter_list NVARCHAR(MAX);DECLARE @first_name_calling_sql NVARCHAR( -)= 'Edward';DECLARE @last_names  aslast_name_table;SELECT  @sql_command = 'INSERT into @last_names (last_name) SELECT LastName from Person.person WHERE FirstName = @first_name_calling_sql; Select Distinctfirstnamefrom person.personwhere LastName in (select Last_Name from @last_names)'SELECT  @parameter_list = '@first_name_calling_sql NVARCHAR, @last_names last_name_table READONLY'EXECsp_executesql@sql_command,@parameter_list,@first_name_calling_sql,@last_names;
View Code

If the INSERT statement is taken out, of course, can be executed, but some business is to deal with the dynamic, amortization hands ...

T-SQL Recipes Table Variables and temporary Tables and CTE

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.