简体   繁体   English

SQL Server中的语法问题,使用OPENROWSET

[英]Syntax issue in SQL Server, using OPENROWSET

I am trying to Execute a stored procedure that requires to variables be passing into to it. 我正在尝试执行一个存储过程,需要将变量传递给它。 One is a static, the other is a dynamic variable. 一个是静态的,另一个是动态变量。

DECLARE @Filt DATETIME 
SET @Filt = (SELECT DISTINCT MAX(Date) FROM Data.db.Staging)
SELECT * INTO #tempData FROM OPENROWSET('SQLNCLI', 'Server=ISR14  \MSSQL2012;Trusted_Connection=yes;', 'EXEC GetData.db.Staging @Mode = ''Date'' @Filt ')

but that doesn't work, got the error back "Msg 8180, Level 16, State 1, Line 1 Statement(s) could not be prepared. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '@Filt'." 但这不起作用,得到错误“消息8180,级别16,状态1,行1语句无法准备。消息102,级别15,状态1,行1''''附近的语法不正确“。

I'm guessing it is because Filt is dynamic statement. 我猜这是因为Filt是动态陈述。 So I tried this 所以我尝试了这个

DECLARE @FilterData DATETIME
DECLARE @sql VARCHAR(200) 
SET @Filt = (SELECT DISTINCT MAX(AsOfDate) FROM Data.db.Staging)
SET @sql = 'EXEC GetData.db.Staging @Mode = ''Date'' @Filt =  '  + @Filt

SELECT * INTO #tempData FROM OPENROWSET('SQLNCLI', 'Server=ISR14\MSSQL2012;Trusted_Connection=yes;',
 @sql)

But I get the message back 但是我收到了回复的消息

"Msg 102, Level 15, State 1, Line 24 Incorrect syntax near '@sql'." “消息102,级别15,状态1,行24'@sql'附近的语法不正确。”

It seems that OPENROWSET can only accept strings. 似乎OPENROWSET只能接受字符串。 But I want to pass a variable that is dynamic. 但我想传递一个动态的变量。

You have to put the whole statement into a variable and run it, and convert @FilterData to a varchar to concatenate it. 您必须将整个语句放入变量并运行它,并将@FilterData转换为varchar以将其连接起来。

You can't use variables with openquery/openrowset. 您不能在openquery / openrowset中使用变量。

Try this and check the print output... if it works and looks ok, then EXEC(@sql2) 试试这个并检查打印输出......如果它工作正常,那么EXEC(@sql2)

DECLARE @FilterData DATETIME
DECLARE @sql VARCHAR(200), @sql2 VARCHAR(500)
SET @FilterData = '2014-07-01'--(SELECT DISTINCT MAX(AsOfDate) FROM Data.db.Staging)
SET @sql = 'EXEC GetData.db.Staging @Mode = ''''Date'''', @Filt =  '''''  + CONVERT(VARCHAR(20),@FilterData ,120) + ''''''

SET @sql2 = 'SELECT * INTO #tempData FROM OPENROWSET(''SQLNCLI'', ''Server=ISR14\MSSQL2012;Trusted_Connection=yes;'',
 '''+@sql+''')'

print @sql2
--exec(@sql2)

You need to make the whole query dynamic, not sure if I got it nailed down, but something like: 你需要使整个查询动态化,不确定我是否已经确定它,但是类似于:

DECLARE @Filt DATETIME 
       ,@sql VARCHAR(MAX)
SET @Filt = (SELECT MAX(Date) FROM Data.db.Staging)
SET @sql = 'SELECT * INTO #tempData FROM OPENROWSET(''SQLNCLI'', ''Server=ISR14  \MSSQL2012;Trusted_Connection=yes;'', ''EXEC GetData.db.Staging @Mode = ''''Date''' +@Filt+ ')'
EXEC (@sql)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM