Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'select'. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ')'.

durai raj s 20 Reputation points
2023-03-18T07:30:26.0766667+00:00

Query

Declare @Sql_Query nvarchar(max)

set @Sql_Query =('select Name,Age,Year,DateofBirth,City,Correction,Time,Id,No From Student.dbo.TestResult where Name=ABCD and Age=21');

set @Sql_Query ='select * from Openquery ([SESDATA],'+@SQL_QUERY+')'

exec sp_executesql @Sql_Query

error

Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'select'.

Msg 102, Level 15, State 1, Line 1

Incorrect syntax near ')'.

SQL Server | Other
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2023-03-18T08:02:04.45+00:00

    Try adjusting one of the lines:

    set @Sql_Query ='select * from Openquery ([SESDATA], ''' + @SQL_QUERY + ''')'
    

    Maybe the real query need some more “'” if parameterised statements cannot be used.


1 additional answer

Sort by: Most helpful
  1. Mojgaan Kataanforoush 0 Reputation points
    2024-08-21T10:52:42.75+00:00

    SELECT country , region, city

    FROM HR.Employees

    ORDER BY country, region, city

    union all

    SELECT country, region, city

    FROM Production.Suppliers

    ORDER BY country, region, city;

    hello after type this query i have problem and show error by union all.

    Incorrect syntax near the keyword 'union'.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.