在执行存储过程时使用函数作为参数?

kru*_*rul 29 t-sql sql-server stored-procedures sql-server-2005

我正在测试存储过程,并希望提交'GETDATE()'函数来代替参数:

DECLARE @return_value int

EXEC @return_value = my_stored_procedure
        @MyId = 1,
        @MyDateField = GETDATE()

SELECT  'Return Value' = @return_value
GO
Run Code Online (Sandbox Code Playgroud)

SQL Server 2005抱怨以下错误:

')'附近的语法不正确.

有人想关注此事吗?

Ode*_*ded 27

您不能直接将函数用作存储过程参数.

您可以执行以下操作:

DECLARE @now DateTime
SET @now = GETDATE()

DECLARE @return_value int
EXEC @return_value = my_stored_procedure
        @MyId = 1,
        @MyDateField = @now
SELECT  'Return Value' = @return_value
GO
Run Code Online (Sandbox Code Playgroud)

  • @Oded:我不确定 krul 是否在乎,但我想知道。为什么存在这个限制?在我知道的几乎所有其他语言中,您都可以使用函数调用作为参数,并且它以预期的方式工作(评估函数,返回值作为参数传递)。为什么 SQL 不允许这样做? (2认同)

Raj*_*aja 14

每个MSDN

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

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

    Execute a pass-through command against a linked server
    { EXEC | EXECUTE }
        ( { @string_variable | [ N ] 'command_string [ ? ]' } [ + ...n ]
            [ { , { value | @variable [ OUTPUT ] } } [ ...n ] ]
        ) 
        [ AS { LOGIN | USER } = ' name ' ]
        [ AT linked_server_name ]
    [;]
Run Code Online (Sandbox Code Playgroud)

注意@parameter可以指定值或变量,也可以指定Default.因此,您必须将变量的值设置为GetDate()(正如其他人指定的那样)并使用该变量.

HTH


Mar*_*ith 10

不允许函数调用作为参数(除了那些前缀的系统函数@@- 即那些曾经被称为全局变量的函数)

您需要分配给变量.

Microsoft承认这在相关的Connect项目中并不是很好:T-SQL:使用标量函数作为存储过程参数

同意!更一般地说,无论TSQL期望什么,比如说和整数值,它都应该接受文字,变量或返回类型为整数的函数的结果.它只是使语言更规则("正交"),更容易学习/使用.

也就是说,Katmai版本中的这个功能为时已晚,但我会将其添加到我们的TODO列表中.