使用MSDASQL使用变量进行远程查询

时间:2014-12-18 15:46:15

标签: tsql sql-server-2008-r2 linked-server openquery msdasql

我正在尝试为SSRS报告创建查询。我需要从链接服务器(到iSeries)获取最近3个月的事务。

所以我构建了一个我想用OpenQuery执行的SQL变量

declare @EarliestDate varchar(8), @SQL VARCHAR(200), @sDate varchar(8)

SET @EarliestDate=CAST(DATEPART(YEAR,DATEADD(m,-3, getdate())) AS VARCHAR(4)) 
    + RIGHT('00' + CAST(DATEPART(mm, DATEADD(m,-3, getdate())) AS varchar(2)), 2)+ '01'

SELECT @SQL= 'SELECT * FROM YEDB03P WHERE TCDAT  >' + '''' + @EarliestDate +'''' + ' ORDER BY TCDAT DESC'
print @EarliestDate
print @SQL

select * from openquery(BOCTEST2,@SQL)

但似乎openquery不喜欢使用变量

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

OPENQUERY不接受其参数的变量。

但您可以将整个OPENQUERY语句移动到动态SQL中:

declare @EarliestDate varchar(8), @SQL VARCHAR(MAX), @sDate varchar(8)

SET @EarliestDate=CAST(DATEPART(YEAR,DATEADD(m,-3, getdate())) AS VARCHAR(4)) 
    + RIGHT('00' + CAST(DATEPART(mm, DATEADD(m,-3, getdate())) AS varchar(2)), 2)+ '01'

SELECT @SQL= 'select * from openquery(BOCTEST2, ''SELECT * FROM YEDB03P WHERE TCDAT  >' + '''''' + @EarliestDate +'''''' + ' ORDER BY TCDAT DESC'')'
print @EarliestDate
print @SQL

EXEC @SQL

答案 1 :(得分:0)

Oleksandr Kucher的帮助下,我设法用下面的代码做了我想做的事情(我在查询字符串中添加char(39)来强制引号):

 declare @EarliestDate varchar(8), @SQL NVARCHAR(1000), @sDate varchar(8)

SET @EarliestDate= CAST(DATEPART(YEAR,DATEADD(m,-3, getdate())) AS VARCHAR(4)) 
    + RIGHT('00' + CAST(DATEPART(mm, DATEADD(m,-2, getdate())) AS varchar(2)), 2)+ '01' 

SELECT @SQL= 'insert into DBO.YEDB03P select * from openquery(BOCTEST2, ''SELECT * FROM YEDB03P WHERE TCDAT  >'+char(39)+CHAR(39) + @EarliestDate  +char(39)+CHAR(39)  + ' ORDER BY TCDAT DESC'')'

--print @SQL

/*
The prints as

insert into DBO.YEDB03P select * from openquery(BOCTEST2, 'SELECT * FROM YEDB03P WHERE TCDAT  >''20141001'' ORDER BY TCDAT DESC')

*/
exec sp_executesql @SQL
select * from PION..YEDB03P

感谢