2011-12-02 74 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關鍵字幾乎和添加值一樣有效)。這不是一個好的通用解決方案,但它在某些使用情況下效果很好。 –