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

Using the result of an expression (e.g. Function call) in a stored procedure parameter list?(在存储过程参数列表中使用表达式(例如函数调用)的结果?)
本文介绍了在存储过程参数列表中使用表达式(例如函数调用)的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a stored procedure to assist with development of our database, but I am having some trouble using it. For example:

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

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

This yields the error (on SQL Server 2005):

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

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

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

Can someone explain to me why my syntax is incorrect, and the right way to solve this problem?

推荐答案

你需要使用一个中间变量.SQL Server虽然已经在TODO列表上好几年了,但它本身并不支持参数列表中的这种操作!(参见 连接项目:使用标量函数作为存储过程参数)

You need to use an intermediate variable. SQL Server does not support this kind of operation in the parameter list itself though it has been on the TODO list for a few years! (See Connect Item: Use scalar functions as stored procedure parameters)

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 也是不允许的).

The documentation is not currently that clear on an acceptable format for value but it seems to be only "simple" expressions such as literal values or @@ prefixed system functions (such as @@IDENTITY). Other system functions such as SCOPE_IDENTITY() are not permitted (even those which do not require parentheses such as CURRENT_TIMESTAMP are not allowed).

所以暂时你需要使用如下的语法

So for the time being you need to use syntax such as the below

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 

这篇关于在存储过程参数列表中使用表达式(例如函数调用)的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)