如何在存储过程中使用openquery?

How to use openquery in stored procedure?

我必须将参数传递给链接服务器并且我必须使用开放式查询,我有如下代码:

DECLARE @TSQL varchar(8000), @VAR char(2)

SELECT @VAR = 'CA'

SELECT @TSQL = 'SELECT * INTO newtable FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ''''' + @VAR + ''''''')'
EXEC (@TSQL)

现在我需要在存储过程中使用它,但出现了不明确的语法错误。我如何在存储过程中使用它?

试试这个:

CREATE PROCEDURE [Name]

AS

DECLARE @TSQL varchar(8000), @VAR char(2)
SET @VAR = 'CA'

SET @TSQL = 'SELECT * INTO newtable FROM OPENQUERY(MyLinkedServer,''SELECT * FROM pubs.dbo.authors WHERE state = ' + @VAR + ' '')'

EXEC (@TSQL)