SQL子句逻辑

时间:2011-06-21 11:23:32

标签: sql-server tsql

我有一个包含id字段和5个字段的表,每周一天从星期一到星期五,其中datatype是bit。

该表格如下:

+---+--------+---------+-----------+----------+--------+
|id | Monday | Tuesday | Wednesday | Thursday | Friday |
+---+--------+---------+-----------+----------+--------+
| 1 |      1 |       0 |         0 |        0 |      0 |
+---+--------+---------+-----------+----------+--------+
| 2 |      1 |       0 |         0 |        0 |      0 |
+---+--------+---------+-----------+----------+--------+
| 3 |      0 |       0 |         0 |        1 |      0 |
+---+--------+---------+-----------+----------+--------+
| 4 |      1 |       0 |         0 |        0 |      1 |
+---+--------+---------+-----------+----------+--------+

根据当天我正在尝试返回当天设置为true的行。我想用where子句做这个,​​但是无法让它工作。

我认为我的逻辑存在问题,非常感谢任何帮助!

DECLARE @tDay as INTEGER
SET @tDay = datepart(weekday, getdate())

SELECT     id, monday, tuesday, wednesday, thursday, friday
FROM         Days
WHERE   CASE WHEN @tDay = 2 then @tDay 
        Else Days.monday
        End = 1
        AND 
        CASE WHEN @tDay = 3 then @tDay 
        Else Days.tuesday
        End = 1 

2 个答案:

答案 0 :(得分:3)

如果SET DATEFIRST为7,这将有效。如果您有其他一天作为一周的第一天,则需要进行调整。

DECLARE @tDay as INTEGER
SET @tDay = datepart(weekday, getdate())

select id, monday, tuesday, wednesday, thursday, friday
from Days
where case @tDay
        when 2 then monday
        when 3 then tuesday
        when 4 then wednesday
        when 5 then thursday
        when 6 then friday
      end = 1

答案 1 :(得分:2)

SELECT     id, monday, tuesday, wednesday, thursday, friday
FROM         Days
WHERE
        CASE @tDay
          WHEN 2 THEN monday
          WHEN 3 THEN tuesday 
          WHEN 4 THEN wednesday
          WHEN 5 THEN thursday
          WHEN 6 THEN friday
          ELSE NULL
        END  = 1