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;
有人看到这里,也许第一直觉就会问,为什么不在动态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;
如果把Insert语句拿出来,当然是可以执行的,不过有些业务就是要动态处理,摊手中……
时间: 2025-01-13 15:10:12