Using function as a parameter when executing a stored procedure?

63,032

Solution 1

per 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 ]
    [;]

Notice for @parameter you can either specify a value or a variable or specify Default. So you got to set the value of a variable as GetDate() (as others have specified) and use that variable.

HTH

Solution 2

You can't use a function directly as a stored procedure parameter.

You can do the following:

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

Solution 3

Function calls as parameters are not allowed (except for those system functions prefixed @@ - i.e. those that used to be called global variables)

You need to assign to a variable.

Microsoft acknowledge this is less than great in this related Connect item: T-SQL: use scalar functions as stored procedure parameters

Agreed! More generally, wherever TSQL expects, say, and integer value, it should accept a literal, a variable, or the result of a function whose return type is integer. It just makes the language more regular ("orthogonal") and easier to learn/use.

That said, it's too late for this feature in the Katmai release, but I'll add it to our TODO list.

Solution 4

You could use

DECLARE @test DATE;
SET @test = GETDATE();

and then

DECLARE @return_value int
EXEC @return_value = my_store procedure
        @MyId = 1,
        @MyDateField = @test
SELECT  'Return Value' = @return_value
GO
Share:
63,032
krul
Author by

krul

Updated on July 05, 2022

Comments

  • krul
    krul almost 2 years

    I'm testing a stored procedure and wanted to submit 'GETDATE()' function in place of parameter:

    DECLARE @return_value int
    
    EXEC @return_value = my_stored_procedure
            @MyId = 1,
            @MyDateField = GETDATE()
    
    SELECT  'Return Value' = @return_value
    GO
    

    SQL Server 2005 complains with following error:

    Incorrect syntax near ')'.

    Anybody care to shed some light on the matter?