Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Variable in OPENROWSET Query

I'm having trouble with this query:

SELECT *  FROM OPENROWSET(     'SQLNCLI',     'DRIVER={SQL Server};',     'EXEC dbo.sProc1 @ID = ' + @id   ) 

Gives an error:

Incorrect syntax near '+'.

Anyone know why I'm getting this error?

like image 462
Control Freak Avatar asked Dec 12 '12 01:12

Control Freak


People also ask

How do you use a variable in Openrowset?

declare @file_stream VARBINARY(MAX) declare @filePath NVARCHAR(128) set @filePath = 'C:\Temp\print4.

What is Openrowset in SQL?

In SQL Server, OPENROWSET can read from a data file without loading the data into a target table. This lets you use OPENROWSET with a simple SELECT statement. Important. Azure SQL Database only supports reading from Azure Blob Storage.

What is Openrowset in Azure?

The OPENROWSET(BULK...) function allows you to access files in Azure Storage. OPENROWSET function reads content of a remote data source (for example file) and returns the content as a set of rows.


2 Answers

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) 
like image 183
praveen Avatar answered Sep 19 '22 16:09

praveen


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...

like image 31
Scott Avatar answered Sep 22 '22 16:09

Scott