sqlsql-server

sql query not working if come as a string


I'm trying to exec SQL SP, and add a "select" to the query. it is working fine, but if I add the "between" I get an error.

This is the code:

DECLARE @query as nvarchar(200);
    SET @query = N'select *
                    from (    
                    select *,totalRecords = COUNT(*) OVER(),ROW_NUMBER() OVER ( ORDER BY date desc) AS RowNum
                        from  #data
                    ) as RowConstrainedResult
                    where RowNum  between 1 and 20
                    ORDER BY RowNum';

    EXEC sp_executesql @query

and this is the error:

Incorrect syntax near '1'.


Solution

  • Try this:

    DECLARE @query as nvarchar(200);
    SET @query = 'select * from (select *,totalRecords = COUNT(*) OVER(),ROW_NUMBER() OVER ( ORDER BY date desc) AS RowNum from  #data) as RowConstrainedResult where RowNum between 1 and 20 ORDER BY RowNum';
    
      select @query              
    
    EXEC sp_executesql @query