从Openquery中删除

时间:2017-10-05 07:41:18

标签: sql openquery

我正在做一个关于链接服务器的项目。由于我们需要传递链接服务器的名称,我想出了这种方法:

DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000), @LinkedServer nvarchar(4000);
DECLARE @name nvarchar(10) = 'Y4081';
SET @LinkedServer = 'linkedserver'
SET @OPENQUERY = 'DELETE FROM OPENQUERY('+ @LinkedServer +', '''
SET @TSQL = 'SELECT * FROM [MyDataBase].[dbo].[MyTable] WHERE Name = ''Y4081'' '')'
EXEC(@OPENQUERY+@TSQL)

但是我收到以下错误: 'Y4081'附近的语法错误。

我在尝试时遇到同样的错误:

DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000), @LinkedServer nvarchar(4000);
DECLARE @name nvarchar(10) = 'Y4081';
SET @LinkedServer = 'linkedserver'
SET @OPENQUERY = 'DELETE FROM OPENQUERY('+ @LinkedServer +', '''
SET @TSQL = 'SELECT * FROM [MyDataBase].[dbo].[MyTable] WHERE Name = ''' + @name + ''' '')'
EXEC(@OPENQUERY+@TSQL)

I'm really stuck at this point and I don't know how to solve it. If you guys could help me I'd be the happiest man alive! Or if you have a better and/or easier approach just tell me!

提前致谢!

2 个答案:

答案 0 :(得分:0)

检查这个。

DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000), @LinkedServer nvarchar(4000);
DECLARE @name nvarchar(10) = 'Y4081';
SET @LinkedServer = 'linkedserver'
SET @OPENQUERY = 'DELETE FROM OPENQUERY('+ @LinkedServer +', '''
SET @TSQL = 'SELECT * FROM [MyDataBase].[dbo].[MyTable] 
WHERE Name = '+@name+' '')'
EXEC(@OPENQUERY+@TSQL)

答案 1 :(得分:0)

DECLARE @OPENQUERY nvarchar(4000), @TSQL nvarchar(4000);
DECLARE @linkedserver nvarchar(100);
DECLARE @name nvarchar(10) = 'Y4081';
SET @linkedserver = 'linkedserver';
SET @OPENQUERY = 'DELETE FROM OPENQUERY('+ @linkedserver +','''
SET @TSQL = 'SELECT * FROM [MyDataBase].[dbo].[MyTable] WHERE Name = ''''' + @name + ''''' '')'
EXEC(@OPENQUERY+@TSQL)

这对我有用;)有点傻了多少''''''你需要在这些开放的东西中。