T-SQL - function with default parameters

前端 未结 4 2012
傲寒
傲寒 2020-11-27 14:45

I have this script:

CREATE FUNCTION dbo.CheckIfSFExists(@param1 INT, @param2 BIT = 1 )
RETURNS BIT
AS
BEGIN
    IF EXISTS ( bla bla bla )
        RETURN 1;
          


        
相关标签:
4条回答
  • 2020-11-27 14:50

    You can call it three ways - with parameters, with DEFAULT and via EXECUTE

    SET NOCOUNT ON;
    
    DECLARE
    @Table  SYSNAME = 'YourTable',
    @Schema SYSNAME = 'dbo',
    @Rows   INT;
    
    SELECT dbo.TableRowCount( @Table, @Schema )
    
    SELECT dbo.TableRowCount( @Table, DEFAULT )
    
    EXECUTE @Rows = dbo.TableRowCount @Table
    
    SELECT @Rows
    
    0 讨论(0)
  • 2020-11-27 14:53

    One way around this problem is to use stored procedures with an output parameter.

    exec sp_mysprocname @returnvalue output, @firstparam = 1, @secondparam=2

    values you do not pass in default to the defaults set in the stored procedure itself. And you can get the results from your output variable.

    0 讨论(0)
  • 2020-11-27 14:54

    you have to call it like this

    SELECT dbo.CheckIfSFExists(23, default)
    

    From Technet:

    When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.

    0 讨论(0)
  • 2020-11-27 15:10

    With user defined functions, you have to declare every parameter, even if they have a default value.

    The following would execute successfully:

    IF dbo.CheckIfSFExists( 23, default ) = 0
        SET @retValue = 'bla bla bla;
    
    0 讨论(0)
提交回复
热议问题