我使用的是sql server 2016,我有一个传感器表,如下所示:
传感器代码传感器状态时间戳PS01AActive2019-11-20 01:38:11.850ps01bactive2019-11-20 02:30:09.850ps01cactive2019-11-20 05:32:11.004PS01活动2019-11-20 07:38:07.997ps01eactive2019-11-20 11:38:06.700
在存储过程中,如何使用日期和班次类型作为输入参数来筛选上面的表?我可以查询筛选日期,但不能查询班次类型。
对于班次类型,请使用下表作为参考:
班次类型StartTimeEndTimeDay06:00:0017:59:59夜间18:00:0005:59:59
这是我的密码
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
1条答案
按热度按时间thtygnil1#
你不能使用
BETWEEN 18 AND 6
这永远不会是真的。也适用于BETWEEN
,检查条件包含在内BETWEEN 6 AND 18
意志意味着>= 6 AND <= 18
这不是你想要的。最好使用>=
以及<
```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
)
)
)
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))
)