【问题标题】:Passing default values of parameters to Table Valued Functions将参数的默认值传递给表值函数
【发布时间】:2013-03-28 19:27:15
【问题描述】:
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 作为参数值传递,就像存储过程一样?

函数确实编译了。

【问题讨论】:

标签: sql sql-server tsql


【解决方案1】:

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

但是,您可以提供 default:

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

或者在这种情况下,如果您知道默认值为 NULL,您可以这样做:

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

还有please always use the schema prefix(在本例中为dbo.)在创建和引用任何对象时,尤其是函数。

【讨论】:

  • 我知道一定有办法。你知道为什么 sprocs 和 TVF 的行为不同的任何特殊原因吗?
  • @wootscootinboogie 我不知道为什么,不,抱歉。
猜你喜欢
  • 2015-01-28
  • 1970-01-01
  • 2015-01-11
  • 1970-01-01
  • 1970-01-01
  • 2012-03-23
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
相关资源
最近更新 更多