Skip to content
Advertisement

Insert data into a table from Open Query with variable

I am trying to using OPENQUERY to pull some data into a table. Here’s what my code looks like:

I end up with the following error:

An INSERT statement cannot contain a SELECT statement that assigns values to a variable.

When I attempt to run the EXEC(@TSQL) without the INSERT it works like a charm, but I am unable to do an insert.

Any ideas how I can possibly resolve this? Thanks.

Advertisement

Answer

You are doing this the wrong way round.

Don’t insert the @TSQL variable into your table, set the variable, then insert the results using INSERT...EXEC...

I’m sure there is an excellent reason you are not just using a straight Linked Server query without dynamic SQL, but I can’t think of one.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement