这个存储过程
CREATE PROC GetPage(@blockNumber int, @blockSize int = 40, @query varchar(1000))
AS
DECLARE @a int = @blockNumber * @blockSize;
DECLARE @b int = @a + @blockSize - 1;
DECLARE @fromPos int = PATINDEX('% FROM %', @query);
DECLARE @from varchar(1000) = SUBSTRING(@query, @fromPos, 1000);
DECLARE @select varchar(1000) = SUBSTRING(@query, 1, @fromPos);
DECLARE @SQL varchar(1000) =
'select *, ROW_NUMBER() over (order by ONE) R INTO #FOO FROM ('
+@SELECT+',1 ONE'+@from+') T';
EXEC @SQL;
SELECT * FROM FOO WHERE RN BETWEEN @a AND @b;
DECLARE @C INT = (SELECT COUNT(*) FROM #FOO);
DROP TABLE #FOO
RETURN @C;
通过时SELECT * FROM ASSET
生成此 SQL
select *, ROW_NUMBER() over (order by ONE) R INTO #FOO
FROM (select * ,1 ONE from asset) T
当我从 SQL Server Management Studio 执行此操作时,如下所示:
exec('select *, ROW_NUMBER() over (order by ONE) R INTO #FOO FROM (select * ,1 ONE from asset) T')
它按预期创建表#FOO。
但是,当执行存储过程时:
exec getpage 5,10,'select * from asset'
我收到这个错误
消息 2812,级别 16,状态 62,过程 GetPage,第 12 行
找不到存储过程'select *,ROW_NUMBER() over (order by ONE) R INTO FOO FROM (select * ,1 ONE from assets) T'。
消息 208,级别 16,状态 1,过程 GetPage,第 14 行
无效的对象名称“#FOO”。
我认为第二条消息仅仅是第一个错误的结果。有谁知道为什么该exec
语句在存储过程中的行为不同?