0

I'm trying to pull back some data via a linked server that has 'Geography' fields present, consequntly I'm trying to use Open Query. I'm also trying to pass in a variable...

Can anyone explain this: This is my sql...

DECLARE @Sql VARCHAR(200)
DECLARE @tnum VARCHAR(20)= 'abc';
SET @Sql = 'SELECT * FROM NationalPolygon.dbo.Polygon WHERE TitleNumber = ''''' + @tnum + '''''';
SET @Sql = 'SELECT * FROM OPENQUERY(mylinkedserver01, ''' + REPLACE(@Sql, '?', '''') + ''')'

SELECT @Sql;
EXEC @Sql;

If I select @Sql and run it, it works. If I run the @Sql via EXEC it fails with:

Database 'SELECT * FROM OPENQUERY(mylinkedserver01, 'SELECT * FROM NationalPolygon' does not exist. Make sure that the name is entered correctly.

Thanks C

1
  • 1
    There are 2 different syntax forms for EXECUTE. One executes the query stored in a string - that requires parentheses around the string (or variable). Commented May 14, 2021 at 12:07

1 Answer 1

1

You need to surround @Sql with brackets

EXEC (@Sql);
Sign up to request clarification or add additional context in comments.

1 Comment

Ta, that's sorted it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.