17
create function Xtest
(@d1 varchar(3)=null
,@d2 varchar(3)=null)
returns table 
as
return 
with code_list(code_pattern)
as
(
    select x.code_pattern
        from (values (@d1),(@d2)) as x(code_pattern)
        where x.code_pattern is not null
),y
as
(
    select substring(code,1,3) as code
        from tblicd
        where substring(code,1,3) in 
        (
            select * from code_list
        )
)

select * from y 

是我的功能,当它完全完成时才有意义。如果我尝试运行此查询并且我不提供两个参数,它将失败。我的代码与存储过程相同,如果我只输入一个参数,它可以正常工作并将第二个参数分配为空。如果没有提供参数,有没有一种方法可以null作为参数值传递,就像存储过程一样?

该函数确实编译。

4

1 回答 1

46

调用函数时不能省略参数。这不是您在语法上做错了什么,只是 SQL Server 不支持它。存储过程具有可选参数,但函数没有。

但是,您可以提供default

SELECT code FROM dbo.Xtest(default, default);

或者在这种情况下,如果您知道默认设置,NULL您可以执行以下操作:

SELECT code FROM dbo.Xtest(NULL, NULL);

在创建和引用任何对象,尤其是函数时,请始终使用模式前缀(在这种情况下)。dbo.

于 2013-03-28T19:28:36.287 回答