gpt4 book ai didi

sql - 在存储过程参数列表中使用表达式(例如函数调用)的结果?

转载 作者:行者123 更新时间:2023-12-02 06:35:26 26 4
gpt4 key购买 nike

我正在尝试编写一个存储过程来协助开发我们的数据库,但我在使用它时遇到了一些问题。例如:

DECLARE @pID int;
SET @pID = 1;
EXEC WriteLog 'Component', 'Source', 'Could not find given id: ' + CAST(@pID AS varchar);

这会产生错误(在 SQL Server 2005 上):

Msg 102, Level 15, State 1, Line 4 Incorrect syntax near '+'.

有人可以向我解释为什么我的语法不正确,以及解决这个问题的正确方法吗?

最佳答案

您需要使用中间变量。 SQL Server 本身不支持参数列表中的这种操作,尽管它已经出现在 TODO 列表中几年了! (参见Connect Item: Use scalar functions as stored procedure parameters)

grammar for EXEC

[ { EXEC | EXECUTE } ]
{
[ @return_status = ]
{ module_name [ ;number ] | @module_name_var }
[ [ @parameter = ] { value
| @variable [ OUTPUT ]
| [ DEFAULT ]
}
]
[ ,...n ]
[ WITH <execute_option> [ ,...n ] ]
}
[;]

文档目前对于 value 可接受的格式尚不清楚,但它似乎只是“简单”表达式,例如文字值或 @@ 前缀系统函数(例如@@IDENTITY)。不允许使用其他系统函数,例如 SCOPE_IDENTITY()(甚至不允许使用不需要括号的函数,例如 CURRENT_TIMESTAMP)。

因此暂时您需要使用如下语法

DECLARE @pID INT;

SET @pID = 1;

/*If 2008+ for previous versions this needs to be two separate statements*/
DECLARE @string VARCHAR(50) = 'Could not find given id: ' + CAST(@pID AS VARCHAR(11))

EXEC WriteLog
'Component',
'Source',
@string

关于sql - 在存储过程参数列表中使用表达式(例如函数调用)的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4936180/

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