gpt4 book ai didi

sql-server - SQL中exec的微妙之处

转载 作者:行者123 更新时间:2023-12-03 10:03:04 25 4
gpt4 key购买 nike

这个存储过程

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'

我收到这个错误

Msg 2812, Level 16, State 62, Procedure GetPage, Line 12
Could not find stored procedure 'select *, ROW_NUMBER() over (order by ONE) R INTO FOO FROM (select * ,1 ONE from asset) T'.
Msg 208, Level 16, State 1, Procedure GetPage, Line 14
Invalid object name '#FOO'.

我认为第二条消息仅仅是第一个错误的结果。有谁知道为什么 exec 语句在存储过程中的行为不同?

最佳答案

在你的exec中使用括号

EXEC (@SQL); 

EXECUTE (Transact-SQL)

没有括号你正在使用这个:

Execute a stored procedure or function[ { EXEC | EXECUTE } ]    {       [ @return_status = ]      { module_name [ ;number ] | @module_name_var }         [ [ @parameter = ] { value                            | @variable [ OUTPUT ]                            | [ DEFAULT ]                            }        ]      [ ,...n ]      [ WITH  [ ,...n ] ]    }[;]

您需要在需要括号的地方使用它。

Execute a character string{ EXEC | EXECUTE }     ( { @string_variable | [ N ]'tsql_string' } [ + ...n ] )    [ AS { LOGIN | USER } = ' name ' ][;]

关于sql-server - SQL中exec的微妙之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15653629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com