T-SQL - 具有默认参数的函数 [英] T-SQL - function with default parameters

查看:95
本文介绍了T-SQL - 具有默认参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



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

我想以这种方式在程序中使用它:

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

但我得到错误:


为过程或函数dbo.CheckIfSFExists提供的参数数量不足。

为什么没有工作?

解决方案

您必须像这样称呼

  SELECT dbo.CheckIfSFExists(23,default)

Technet


当函数的参数具有默认值时,必须在调用该函数时指定关键字
DEFAULT,以便
检索默认值。这种行为不同于在存储过程中使用
参数和默认值,其中省略
该参数也意味着默认值。此
行为的一个例外是使用EXECUTE
语句调用标量函数时。使用EXECUTE时,不需要DEFAULT关键字。



I have this script:

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

I want to use it in a procedure in this way:

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

But I get the error:

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

Why does it not work?

解决方案

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 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.

这篇关于T-SQL - 具有默认参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆