Using a Variable in OPENROWSET Query

本秂侑毒 提交于 2019-11-26 17:44:19

As suggested by Scott , you cannot use expressions in OPENROWSET.Try creating a dynamic sql to pass the parameters

Declare @ID int
Declare @sql nvarchar(max)
Set @ID=1
Set @sql='SELECT * 
FROM OPENROWSET(
               ''SQLNCLI'',
               ''DRIVER={SQL Server};'',
               ''EXEC dbo.usp_SO @ID =' + convert(varchar(10),@ID) + ''')'

-- Print @sql
 Exec(@sql)

OPENROWSET requires string literals, not expressions. It's complaining about the plus sign, becaue it doesn't expect anything more than a string literal and you follewed the string literal with an operator.

See http://msdn.microsoft.com/en-us/library/ms190312.aspx which states:

'query'

Is a string constant sent to and executed by the provider...

Declare @Route VARCHAR(200)
Declare @sql nvarchar(max)
Set @Route='C:\OCRevisiones.xlsx;'
Set @sql='SELECT * INTO FFFF
FROM OPENROWSET(
               ''Microsoft.ACE.OLEDB.12.0'',
               ''Excel 12.0;HDR=YES;Database=' + @Route + ''',
               ''SELECT * FROM [Sheet1$]'')'

 Print @sql
 --Exec(@sql)

For what it is worth.. The reason we use openrowset rather than a straight linked server query is that the processing for a linked server query happens on the local server. (Slow and often brings most of the table back)

Yes we can do the string concatination as above.

A different option where you have ease of syntax and the power of parameters.

Create a stored proc on the remote box, that proc has all the parameters you need. Call the stored proc from with a standard linked server query (same perf or better than the above soultion and significantly easier to code with.

e.g. linkedservername.database.dbo.myproc 123,'abc','someparam',getdate()

Just an option....

harmath

If you need parameters you can also use sp_executesql:

BEGIN

DECLARE
@p_path varchar(200)='D:\Sample\test.xml',  
@v_xmlfile xml,
@v_sql nvarchar(1000)

SET @v_sql=N'select @v_xmlfile= CONVERT(XML, BulkColumn) FROM 
OPENROWSET(BULK '''+@p_path+''', SINGLE_BLOB) AS x;'

EXEC sp_executesql @v_sql,N'@v_xmlfile xml output',@v_xmlfile output;

SELECT @v_xmlfile

END
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!