可以像在存储过程中那样在函数内部使用默认参数吗?

Can you use default parameters inside functions, like you can in stored procedures?

我正在尝试在函数(而不是存储过程)中包含默认参数。我无法让它工作,我在没有传递默认参数的情况下尝试调用它的任何地方都会给我错误'..insufficient parameters..'.

是否可以对以下任何一项使用默认参数,如果可以,似乎必须不同地处理,那么您是如何做到的:

我试过用谷歌搜索这个,并通过 SO 进行搜索,但我能找到的所有内容都只处理存储的参数,这在这种情况下不起作用。


编辑:这就是我尝试创建函数的方式:

CREATE FUNCTION MyFunction (@firstparam bit, @secondparam bit = 1) RETURNS @retparam table (columnname bit)

然后我会尝试用类似

的方式来调用它
SELECT *
    FROM table1
    WHERE table1.uid IN (select columnname from dbo.MyFunction(1))

这会导致错误“..参数不足..”

评论太长了。

估计只有真正绝望的样子了documentation。很明显,默认参数是受支持的。这是语法的相关部分:

CREATE FUNCTION [ schema_name. ] function_name( [ { @parameter_name [

AS ][ type_schema_name. ] parameter_data_type

[ = **default** ] [ READONLY ] } 

[ ,...n ]   ] )

再往下一点:

[ = default ]

Is a default value for the parameter. If a default value is defined, the function can be executed without specifying a value for that parameter.

您没有提供有关您在做什么的提示,但函数不使用 default 关键字。他们只是使用 =.

您可以对参数使用默认值,但不能像对过程那样使用。您必须指定所有参数,并为要使用默认值的参数使用关键字 default

create function dbo.GetIt(@P1 int = -1) returns int
as
begin
  return @P1;
end

go

select dbo.GetIt(default);

结果:

-1

发件人:CREATE FUNCTION (Transact-SQL)

When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called 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. However, the DEFAULT keyword is not required when invoking a scalar function by using the EXECUTE statement.