Search code examples
sqlsql-serveropenquery

SQL OPENQUERY, Incorrect syntax near '+'


I have this sql query:

DECLARE  @VAR varchar(8)
SET  @VAR = '20140202'
SELECT * FROM OPENQUERY([NMD],'SELECT * FROM NmdItemGroups01.dbo.InvTranDtl WHERE TranDate = ''' + @VAR + '''')

But when I run it, it gives this error:

Incorrect syntax near '+'

Solution

  • sp_executesql example:

    DECLARE  @VAR varchar(8)
    SET  @VAR = '20140202'
    
    EXEC sp_executesql 
        N'SELECT * FROM NmdItemGroups01.dbo.InvTranDtl WHERE TranDate = @TranDate', 
        N'@TranDate DATE', 
        @VAR