2011-12-02 118 views
110

我有这样的脚本:T-SQL - 函数的默认参数

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

我想在这样一个过程来使用它:

IF dbo.CheckIfSFExists(23) = 0 
    SET @retValue = 'bla bla bla'; 

但我得到的错误:

An insufficient number of arguments were supplied for the procedure or function dbo.CheckIfSFExists.

为什么它不起作用?

回答

166

你要这样称呼它

SELECT dbo.CheckIfSFExists( 23, default) 

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 behavior 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 behavior is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.

+49

看到这我感到沮丧。我在这里没有得到'默认'概念的优势...我现在需要去改变所有的地方。 – Lijo

+5

@Lijo,您仍然可以在每次调用时不重复具体的默认值。 –

14

使用用户定义的函数,即使它们具有默认值,也必须声明每个参数。

下将成功执行:

IF dbo.CheckIfSFExists(23, default) = 0 
    SET @retValue = 'bla bla bla; 
24

你可以称它为三种方式 - 与参数,与默认和通过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

解决此问题的一种方法是使用具有输出参数的存储过程。

EXEC sp_mysprocname @returnvalue输出,@firstparam = 1,@ secondparam = 2倍

的值,在不默认为在存储过程本身设置的默认值通过。你可以从你的输出变量中得到结果。

+0

将函数更改为存储过程通常不是一个好的解决方案,因为存储过程不能从查询中调用,但函数可以。 – Blade

+0

确实如此,但并非所有代码块都需要从查询中调用。已经表明,sql没有一个好的方法来处理函数的默认值(使用default关键字几乎和添加值一样有效)。这不是一个好的通用解决方案,但它在某些使用情况下效果很好。 –