T-SQL Recipes之 Table Variables and Temporary Tables and CTE

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了T-SQL Recipes之 Table Variables and Temporary Tables and CTE相关的知识,希望对你有一定的参考价值。

Problem

许多时候, 我们想要Table Variables在动态SQL中执行,但现实是很骨感的。比如这个示例:

技术分享
DECLARE @sql_command NVARCHAR(MAX);
DECLARE @parameter_list NVARCHAR(MAX);
DECLARE @last_names TABLE ( last_name NVARCHAR(50) );
SELECT  @sql_command = 
SELECT DISTINCT
FirstName
FROM Person.Person
WHERE LastName IN (SELECT last_name FROM @last_names)
EXEC sp_executesql @sql_command;
View Code

有人看到这里,也许第一直觉就会问,为什么不在动态SQL中申明@last_names,其实然并卵。

这条路走不通,那我们换条路吧,比如Type Table:

技术分享
CREATE TYPE last_name_table AS TABLE
(last_name NVARCHAR(50));
GO
--DROP TYPE last_name_table
DECLARE @sql_command NVARCHAR(MAX);
DECLARE @parameter_list NVARCHAR(MAX);
DECLARE @first_name_calling_sql NVARCHAR(50) = Edward;
DECLARE @last_names AS last_name_table;



SELECT  @sql_command = 
INSERT  INTO @last_names
        ( last_name
        )
        SELECT  LastName
        FROM    Person.Person
        WHERE   FirstName = @first_name_calling_sql;

SELECT DISTINCT
FirstName
FROM Person.Person
WHERE LastName IN (SELECT last_name FROM @last_names)

SELECT  @parameter_list = @first_name_calling_sql NVARCHAR(50), 
@last_names last_name_table READONLY
EXEC sp_executesql @sql_command, @parameter_list, @first_name_calling_sql,@last_names;
View Code

如果把Insert语句拿出来,当然是可以执行的,不过有些业务就是要动态处理,摊手中……

 

以上是关于T-SQL Recipes之 Table Variables and Temporary Tables and CTE的主要内容,如果未能解决你的问题,请参考以下文章

T-SQL Recipes之Dynamic PIVOT and UNPIVOT

T-SQL Recipes之Index Defragmentation

T-SQL Recipes之Customized Database Objects

十九curator recipes之PathChildrenCache

二十curator recipes之NodeCache

curator recipes之屏障barrier