我试图执行sql SP,然后添加"选择"到查询。 它工作正常,但如果我在"之间添加"我收到了错误。
这是代码:
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
这是错误:
Incorrect syntax near '1'.
答案 0 :(得分:1)
变量声明问题
DECLARE @query as nvarchar(200);
^^^
由于您的变量包含不适用于此变量的多行sql语句,请尝试对此多行sql语句使用MAX大小变量
DECLARE @query as nvarchar(MAX);
答案 1 :(得分:0)
试试这个:
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
答案 2 :(得分:0)
我认为问题出在DECLARE @query as nvarchar(200);
将其更改为DECLARE @query as nvarchar(MAX);
您应该PRINT @query
在执行
答案 3 :(得分:0)
您已声明@query as nvarchar(200)
且查询长度超过200,因此只需将@query as nvarchar(200)
更改为@query as nvarchar(2000)
,它就可以正常使用。