SQL查询运行良好,但不是由它生成的函数

时间:2018-04-29 17:05:38

标签: sql sql-server function

我正在尝试创建一个返回飞行持续时间的函数。

它适用于简单的查询,但是当我尝试使用该函数时,它返回0 ...

返回1:00

declare @FlightId int,
        @Departure datetime,
        @Arrival datetime,
        @duration varchar

set @FlightId = (select FlightId from Flight where FlightNumber = 'ZZZ')
set @Departure = (select min(Departure) from Step where FlightId = @FlightId )
set @Arrival = (select max(Arrival) from Step where FlightId = @FlightId )

select CONVERT(varchar(5), DATEADD(minute, DATEDIFF(minute, @Departure, @Arrival), 0), 114)

这是返回0的函数

alter function FlightDuration
    (@FlightNumber varchar(50)) 
returns varchar
as 
begin
    declare @FlightId int,
            @Departure datetime,
            @Arrival datetime,
            @duration varchar

    set @FlightId = (select FlightId from Flight where FlightNumber = @FlightNumber)
    set @Departure = (select min(Departure) from Step where FlightId = @FlightId )
    set @Arrival = (select max(Arrival) from Step where FlightId = @FlightId )

    set @duration = CONVERT(varchar(12), DATEADD(minute, DATEDIFF(minute, @Departure, @Arrival), 0), 114)

    return @duration
end

我称之为:

SELECT dbo.FlightDuration ('ZZZ')

2 个答案:

答案 0 :(得分:2)

问题很容易就是varchar上的长度属性。如果没有长度,SQL Server默认长度为“1”。

因此,尝试将函数声明为:

alter function FlightDuration (
    @FlightNumber varchar(50)
) returns varchar(12)
begin
    . . .
end;

答案 1 :(得分:0)

我猜飞机'ZZZ'不存在。在第一种情况下,/(db\.[a-z]+\.[a-z]+\(([^)]+)\)(;|$))/i可能已由先前的查询设置。要检查查询是否成功,请执行以下操作:

@FlightId