从参数动态tSQL查询

时间:2018-02-09 14:50:45

标签: sql sql-server excel tsql dynamic-sql

我正在努力使用tSQL中的动态查询来与Excel ODBC一起使用。

SQL Server 2016通过ODBC驱动程序11 for SQL Server

我找到了这篇文章,但它只使用存储在参数中的表名,我需要将实际表放在参数中:Simple dynamic TSQL query syntax

declare @t table(value1 int, value2 nvarchar(1024))
insert @t SELECT 1 as value1, 'test' as value2
declare @where nvarchar(max)
declare @query nvarchar(max)
declare @sql nvarchar(max)
set @where = ' WHERE value1 = 1'
set @query = 'Select * from @t'
set @sql = @query + @where
EXEC(@sql)

这会导致错误消息必须声明表变量" @ t"

不幸的是我无法使用临时表,因为连接器不支持临时表。

我的原始查询要复杂得多,包含6个不同的参数,所有参数都在不同的点注入查询,2个表参数保存临时结果

提前致谢

1 个答案:

答案 0 :(得分:1)

您只需将表格声明为查询的一部分即可。该表在该范围内被声明和识别:

declare @t table(value1 int, value2 nvarchar(1024))
insert @t select 1 as value1, 'test' as value2
declare @where nvarchar(max)
declare @query nvarchar(max)
declare @sql nvarchar(max)
set @where = ' where value1 = 1'
set @query = 'declare @t table(value1 int, value2 nvarchar(1024)) 
              insert @t select 1 as value1, ''test'' as value2 
              select * from @t'
set @sql = @query + @where
exec(@sql)

结果:

enter image description here