问题
I'm trying the following Sql query to move my stored procedure result into table
SELECT *
INTO #tmpTable
FROM OPENQUERY(WIN2K8\SQL2K12, 'EXEC vcs_gauge @gauge_name=vs1_bag,@first_rec_time=2014-09-01 09:00:00,@last_rec_time=2014-09-01 10:00:00')
following error is thrown, when I execute the query.
Incorrect syntax near '\'.
I don't want to add linked server .How to resolve this issue?
EDIT1
When I do [win2k8\sql2k12], and first execute the following command
EXEC sp_serveroption 'YourServer', 'DATA ACCESS', TRUE
A new message comes
OLE DB provider "SQLNCLI11" for linked server "WIN2K8\SQL2K12" returned message "Deferred prepare could not be completed.". 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 '-'.
回答1:
You need to enclose DATETIME values in single quotes. And since your query is in a string itself, those single-quotes need to be doubled / escaped as follows (and you should probably also put the first parameter's value in escaped-single-quotes as it is clearly a string).
You should also fully qualify the stored procedure name with [DatabaseName].[SchemaName].
.
And since the vcs_gauge
proc uses Dynamic SQL, you need to specify the WITH RESULT SETS
clause. For more info on this clause, please see the MSDN page for EXECUTE.
SELECT *
INTO #tmpTable
FROM OPENQUERY([WIN2K8\SQL2K12],
N'EXEC [DatabaseName].[SchemaName].vcs_gauge
@gauge_name = ''vs1_bag'',
@first_rec_time = ''2014-09-01 09:00:00'',
@last_rec_time = ''2014-09-01 10:00:00''
WITH RESULT SETS ( { column_specification} );
');
来源:https://stackoverflow.com/questions/27799091/openquery-throws-error-when-used-with-win2k8-sql2k12