Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL cast parameter on the fly when calling a stored procedure

Why the following code

DECLARE @LogDetail AS NVARCHAR(1000)
SELECT @LogDetail = CAST(@@ROWCOUNT AS NVARCHAR(30)) + ' rows processed'
EXECUTE MyProcedure @ExecutionId, @LogDetail

works, but this doesn't?

EXECUTE MyProcedure @ExecutionId, CAST(@@ROWCOUNT AS NVARCHAR(30)) + ' rows processed'

It is strange since a value produced on the fly works with an INSERT statement, but not when calling a procedure.

How can I do it with a singleline of code?

Thanks

like image 932
Shepard Avatar asked Mar 19 '15 12:03

Shepard


1 Answers

Because you have to use variables or values when using EXEC. expressions aren't an option.

-- SQL Server Syntax

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

And, since you mention INSERT we can look at it and see that it does explicitly mention expressions:

[ WITH <common_table_expression> [ ,...n ] ]
INSERT 
{
        [ TOP ( expression ) [ PERCENT ] ] 
        [ INTO ] 
        { <object> | rowset_function_limited 
          [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]
        }
    {
        [ ( column_list ) ] 
        [ <OUTPUT Clause> ]
        { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n     ] 
        | derived_table 
        | execute_statement
        | <dml_table_source>
        | DEFAULT VALUES 
        }
    }
}
[;]

How can I do it with a singleline of code?

As bizarre as it sounds, you can't. If you want to construct the information to pass to a stored procedure, you have to do that as a separate SET/SELECT to get it into a variable.

like image 75
Damien_The_Unbeliever Avatar answered Oct 08 '22 19:10

Damien_The_Unbeliever