【问题标题】:Pass temp table to EXEC sp_executesql将临时表传递给 EXEC sp_executesql
【发布时间】:2016-08-08 18:32:01
【问题描述】:

如何将临时表 (@table) 传递给 EXEC sp_executesql @query

    set @query = 'SELECT GsName, ' + @cols + ' from 
        (
            select GSName, [THour], NumOfTransactions
            from @table
       ) x
        pivot 
        (
             max([NumOfTransactions])
            for [THour] in (' + @cols + ')
        ) p '

【问题讨论】:

标签: sql exec temp-tables sp-executesql ssms-2014


【解决方案1】:

你这里的不是Temporary Table,而是Table-Valued Parameter

表值参数使用自定义表声明 类型。您可以使用表值参数发送多行 数据到 Transact-SQL 语句或例程,例如存储的 过程或函数,无需创建临时表或许多 参数。

sp_executesql 确实支持表值参数,但它们必须是声明类型。

-- So, first we must declare User-Defined Table Type 
CREATE TYPE udtYB_Test AS TABLE(GSName nvarchar(100), THour time, NumOfTransactions int);
GO

-- Now we can create Table-Valued Parameter
Declare @table udtYB_Test;

-- And store there some data
Insert Into @table (GSName, THour, NumOfTransactions)
Values ('Sample', SYSUTCDATETIME(), 1);

-- Just for the reference
Select * From @table;

-- To pass variable to sp_executesql we need parameters definition
DECLARE @ParmDefinition nvarchar(500) = N'@table udtYB_Test READONLY';
-- Please note: table-valued parameter must be READONLY

-- Here I use simplified query for demonstration only
DECLARE @query nvarchar(500) = 'SELECT * FROM @table';

-- and the result should be identical to the reference above
EXECUTE sp_executesql @query, @ParmDefinition, @table = @table;

-- User-Defined Table Type cleanup
DROP TYPE udtYB_Test;
GO

在大多数实际情况下,使用临时表要容易得多:

Create Table #table (GSName nvarchar(100), THour time, NumOfTransactions int);
Insert Into #table (GSName, THour, NumOfTransactions) Values ('Sample', SYSUTCDATETIME(), 1);
Select * From #table;
DECLARE @query nvarchar(500) = 'SELECT * FROM #table';
EXECUTE sp_executesql @query;
Drop Table #table;

【讨论】:

    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 2023-03-30
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多