Skip to content
Advertisement

DELETE FROM Openquery

I’m doing a project at work regarding linked servers. As we need to pass the name of the linked server I came up with this approach:

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)

But I get the following error: Wrong syntax near ‘Y4081’.

I get the same error when trying it that way:

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! Thanks in advance!

Advertisement

Answer

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)

This worked for me 😉 Kinda silly how many ””” you need in these openquery things.

4 People found this is helpful
Advertisement