计算datediff存储过程时获取语法错误

时间:2014-04-11 07:56:49

标签: sql sql-server stored-procedures

我有一个这样的存储过程:

alter procedure [dbo].[IBS_fetchreqVehicleinPodiumtestnew1]
   @locid INTEGER = NULL
AS BEGIN
   SET NOCOUNT ON

   DECLARE @TodayMinus7Days DATETIME
Declare @krrt integer
Declare @DT integer
   SET @TodayMinus7Days = getdate()-7

   SELECT  
       t.TBarcode, t.PlateNo, t.DelEcode
       if t.status=3
       begin
       @krrt=datediff(MINUTE, t.PayDate, GETDATE())
         end
         else
         if t.status=4
         begin
         @krrt=datediff(MINUTE, t.PayDate, t.t.KeyRoomDate)
         end
         if t.status=5
         begin 
         @dt=datediff(minute,t.paydate,t.Deldate)
         end
   FROM    
       dbo.Transaction_tbl t
   WHERE   
       ([status] IN (3,4) AND locid = @locid AND dtime >= @TodayMinus7Days)
       OR 
       ([status] = 5 AND DATEDIFF(n, CAST(DelDate AS DATETIME), GETDATE()) <= 3 AND locid = @locid AND dtime >= @TodayMinus7Days)
   ORDER BY  
       paydate
END

在执行存储过程时,如果相应的Tbarcode状态为3,那么我想显示paydate和当前时间之间的差异。如果状态为4,那么我想显示t.paydate和t.keyroomdate之间的差异,如果状态是5然后我想显示该特定日期之间的差异......但在执行此存储过程时会收到错误。

2 个答案:

答案 0 :(得分:1)

如果您只想将这些DATEDIFF结果作为结果集中的另一列检索,则应该只是:

   SELECT  
       t.TBarcode, t.PlateNo, t.DelEcode
       datediff(MINUTE, t.PayDate,
             CASE t.Status
                WHEN 3 THEN GETDATE()
                WHEN 4 THEN t.KeyRoomDate
             END) as KRRT,
       datediff(MINUTE,t.PayDate,
             CASE t.Status
                WHEN 5 THEN t.DelDate
             END) as DT
   FROM    
       dbo.Transaction_tbl t
   WHERE   
       ([status] IN (3,4) AND locid = @locid AND dtime >= @TodayMinus7Days)
       OR 
       ([status] = 5 AND DATEDIFF(n, CAST(DelDate AS DATETIME), GETDATE()) <= 3
         AND locid = @locid AND dtime >= @TodayMinus7Days)
   ORDER BY  
       paydate

答案 1 :(得分:0)

alter procedure [dbo].[IBS_fetchreqVehicleinPodiumtestnew1]
   @locid INTEGER = NULL
AS BEGIN
   SET NOCOUNT ON

   DECLARE @TodayMinus7Days DATETIME
   SET @TodayMinus7Days = getdate()-7

   SELECT  
       t.TBarcode, t.PlateNo, t.DelEcode
       ,case 
            when t.status=3 then datediff(MINUTE, t.PayDate, GETDATE())
        when t.status=4 then datediff(MINUTE, t.PayDate, t.t.KeyRoomDate)
        else null
    end AS krrt
    , case
        when t.status=5 then datediff(minute,t.paydate,t.Deldate)
        else null
    end as DT
   FROM    
   dbo.Transaction_tbl t
   WHERE   
   ([status] IN (3,4) AND locid = @locid AND dtime >= @TodayMinus7Days)
   OR 
   ([status] = 5 AND DATEDIFF(n, CAST(DelDate AS DATETIME), GETDATE()) <= 3 AND locid = @locid AND dtime >= @TodayMinus7Days)
   ORDER BY  
   paydate

END