简体   繁体   中英

Date and shift time type filter in stored procedure

I am using SQL Server 2016 and I have a sensor table as follow:

SensorCode SensorStatus Timestamp
PS01A Active 2019-11-20 01:38:11.850
PS01B Active 2019-11-20 02:30:09.850
PS01C Active 2019-11-20 05:32:11.004
PS01D Active 2019-11-20 07:38:07.997
PS01E Active 2019-11-20 11:38:06.700

How can I filter above table with date and shift type as input parameter in stored procedure? I can make the query for filter the date but not the shift type.

For the shift type use below table as reference:

ShiftType StartTime EndTime
Day 06:00:00 17:59:59
Night 18:00:00 05:59:59

and here is my code

ALTER PROCEDURE [dbo].[GET_SENSOR_STATE]
@date DATE,
@shifttypeid INT,
@shifttype NVARCHAR(MAX)

AS

BEGIN

SET NOCOUNT ON;

IF (@shifttype = 'DAY')
SET @shifttypeid = 0
ELSE
SET @shifttypeid = 1
    
SELECT [SensorCode]
      ,[SensorStatus]
      ,[Timestamp]

FROM [MyTable].[dbo].[SensorState] SS

WHERE
--@date = CAST(SS.Timestamp AS DATE)
CASE @shifttypeid
WHEN 0 THEN @date = CAST(SS.Timestamp AS DATE) AND DATEPART(HH, SS.Timestamp) BETWEEN 6 AND 18
WHEN 1 THEN @date = CAST(SS.Timestamp AS DATE) AND DATEPART(HH, SS.Timestamp) BETWEEN 18 AND 6
END

END 

You can't use BETWEEN 18 AND 6 it will never be true. Also for BETWEEN , the checking condition is inclusive BETWEEN 6 AND 18 will means >= 6 AND <= 18 which is not exactly what you want. It is best to use >= and <

WHERE (
          CAST(SS.Timestamp AS DATE) = @date
      OR  (    
               @shifttypeid = 1 
           AND CAST(SS.Timestamp AS DATE) = DATEADD(DAY, 1, @date)
          )
      )
AND   (
          (    -- Day Shift
               @shifttypeid = 0
          AND  DATEPART(HH, SS.Timestamp) >= 6
          AND  DATEPART(HH, SS.Timestamp) < 18
          )
      OR  (    -- Night Shift
               @shifttypeid = 1
          AND  (
                   DATEPART(HH, SS.Timestamp) < 6
               OR  DATEPART(HH, SS.Timestamp) >= 18
               )
          )
      )

Added condition to handle Night Shift Date


EDIT: based on @shifttypeid filter the required Timestamp accordingly.

WHERE  (    -- Day Shift 06:00 to 18:00
            @shifttypeid = 0
       AND  SS.Timestamp >= DATEADD(HOUR,  6, CAST(@date AS DATETIME))
       AND  SS.Timestamp <  DATEADD(HOUR, 18, CAST(@date AS DATETIME))
       )   
OR     (    -- Night Shfit 18:00 to 06:00
            @shifttypeid = 1
       AND  SS.Timestamp >= DATEADD(HOUR, 18, CAST(@date AS DATETIME))
       AND  SS.Timestamp <  DATEADD(HOUR, 30, CAST(@date AS DATETIME))
       )   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM