If you print the @Query
value, you will see the error root. So if you run the following code:
DECLARE @DOMAIN NVARCHAR = N'XXX';
DECLARE @QUERY NVARCHAR(MAX)= '
SELECT * FROM OPENQUERY( [XX\XX],''
SELECT CONCAT(CONCAT([Firstname],''),[Lastname]) AS [Owner]
FROM [XXX].[dbo].[Employee] '')'
PRINT @QUERY
You will get the following result:
SELECT * FROM OPENQUERY( [XX\XX],'
SELECT CONCAT(CONCAT([Firstname],'),[Lastname]) AS [Owner]
FROM [XXX].[dbo].[Employee] ')
Now it is clear why SQL Server returns the
Unclosed quotation mark after..
To solve it you need to keep in mind that, in order to have a single quote mark in the output in a string variable, you need to put two single quote mark.
Now you need to rewrite it as below:
DECLARE @DOMAIN NVARCHAR = N'XXX';
DECLARE @QUERY NVARCHAR(MAX)= '
SELECT * FROM OPENQUERY( [XX\XX],''
SELECT CONCAT(CONCAT([Firstname],''''),[Lastname]) AS [Owner]
FROM [XXX].[dbo].[Employee] '')'
PRINT @QUERY
aforementioned query will produce:
SELECT * FROM OPENQUERY( [XX\XX],'
SELECT CONCAT(CONCAT([Firstname],''),[Lastname]) AS [Owner]
FROM [XXX].[dbo].[Employee] ')
You can now simply replace Print
with EXECUTE
command and execute it!