T-SQL: Cannot pass concatenated string as argument to stored procedure

后端 未结 3 2086
梦如初夏
梦如初夏 2020-12-09 09:38

Scenario: Need to pass n arguments to a stored procedure. One of the arguments is of type varchar(x). That varchar argument needs to b

相关标签:
3条回答
  • 2020-12-09 09:39

    It's a limitation on the EXEC statement. See The curse and blessings of dynamic SQL for more information.

    0 讨论(0)
  • 2020-12-09 10:02

    The EXECUTE statement simply has a different grammar then other statements like SELECT and SET. For instance, observe the syntax section at the top of the following two pages.

    EXECUTE statement: http://msdn.microsoft.com/en-us/library/ms188332.aspx

    SET statement: http://msdn.microsoft.com/en-us/library/ms189484.aspx

    The syntax for EXECUTE only accepts a value

    [[@parameter =] {value | @variable [OUTPUT] | [DEFAULT]]

    Whereas the syntax for SET accepts an expression

    {@local_variable = expression}

    A value is basically just a hard coded constant, but an expression is going to be evaluated. It's like having the varchar 'SELECT 1 + 1'. It's just a varchar value right now. However, you can evaluate the string like this:

    EXEC('SELECT 1 + 1')
    

    I suppose all I'm pointing out is that the EXEC command doesn't allow expressions by definition, which you apparently found out already. I don't know what the intention of the developers of T-SQL where when they made it that way. I suppose the grammar would just get out of hand if you where allowed to throw subqueries within subqueries in the parameter list of a stored procedure.

    T-SQL Expression: http://msdn.microsoft.com/en-us/library/ms190286.aspx

    0 讨论(0)
  • 2020-12-09 10:04

    You cannot do something like this either

    exec SomeProc getdate()
    

    you have to put all that stuff in a param like you are doing at your bottom query It might be because it is non deterministic (at least for functions)

    0 讨论(0)
提交回复
热议问题