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

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


DECLARE @pID int;

SET @pID = 1;

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

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


消息102,级别15,状态1,第4行'+'附近的语法不正确。


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


汪汪一只猫
浏览 659回答 3
3回答

慕码人8056858

您需要使用一个中间变量。尽管SQL Server已经出现在TODO列表中有几年了,但它本身在参数列表中不支持这种操作!(请参阅“ 连接项目:使用标量函数作为存储过程参数”)的语法EXEC是[ { EXEC | EXECUTE } ]&nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; [ @return_status = ]&nbsp; &nbsp; &nbsp; { module_name [ ;number ] | @module_name_var }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; [ [ @parameter = ] { value&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| @variable [ OUTPUT ]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;| [ DEFAULT ]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; [ ,...n ]&nbsp; &nbsp; &nbsp; [ WITH <execute_option> [ ,...n ] ]&nbsp; &nbsp; }[;]该文档目前尚不清楚可接受格式,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&nbsp; 'Component',&nbsp; 'Source',&nbsp; @string&nbsp;

哆啦的时光机

您不能对存储过程的参数进行操作。您应该在另一个变量上分配该值,然后将其传递给SP。DECLARE @pID int, @nameId VARCHAR(100);SET @pID = 1;SET @nameId = 'Could not find given id: ' + CAST(@pID AS varchar);EXEC WriteLog 'Component', 'Source', @nameId
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

SQL Server