一分为二,让返回table的Function使用逻辑判断

在SQL Server 2005中,函数分为三种:返回单值函数,返回内联table函数,返回多语句table函数,在返回table的函数中是不能使用逻辑的判断和其他语句的,只能使用查询语句。如果遇到这种情况,应该把需要进行逻辑判断的部分封装到另外的返回单值的函数里。

比如如下的代码是不能运行的:

Create Function [dbo].[F_BindedSuppliers](@SupplierID int)
RETURNS TABLE
as return
(
declare @MainSupplierID int

if exists(select 1 from dbo.SupplierBinder where MainSupplierID=@SupplierID)
begin
	set @MainSupplierID=@SupplierID
end

else if exists(select 1 from dbo.SupplierBinder where SubSupplierID=@SupplierID)
	select @MainSupplierID=MainSupplierID from dbo.SupplierBinder where SubSupplierID=@SupplierID

if @MainSupplierID is null
	select @SupplierID as SupplierID
else
	select @MainSupplierID as SupplierID
		union
	select SubSupplierID from SupplierBinder where MainSupplierID= @MainSupplierID
)

这样将会收到语法错误的报告。进行逻辑函数拆分后,代码如下:

go

CREATE FUNCTION [dbo].[GetMainSupplieID]
(@SupplierID int)
RETURNS int
AS
BEGIN
declare @MainSupplierID int

if exists(select 1 from dbo.SupplierBinder where MainSupplierID=@SupplierID)
begin
	set @MainSupplierID=@SupplierID
end

else if exists(select 1 from dbo.SupplierBinder where SubSupplierID=@SupplierID)
	select @MainSupplierID=MainSupplierID from dbo.SupplierBinder where SubSupplierID=@SupplierID
if @MainSupplierID is null
	set  @MainSupplierID=@SupplierID

	return @MainSupplierID
END

go

Create Function [dbo].[F_BindedSuppliers](@SupplierID int)
RETURNS TABLE
as return
(
	select [dbo].[GetMainSupplieID](@SupplierID) as SupplierID
		union
	select SubSupplierID from SupplierBinder where MainSupplierID= [dbo].[GetMainSupplieID](@SupplierID)
)

go
这样就可以顺利实现预想功能了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值