SQL Server:SELECT和CASE

时间:2012-11-18 12:24:43

标签: sql-server case

我正在尝试根据传递给我的存储过程的一些参数来选择数据。我有年龄问题,我想做这样的事情:

如果我的存储过程参数@Age = 1然后我选择15到18之间的年龄,@Age = 2然后是19 - 25 ......,显然这是不正确的,任何人都可以提供帮助。感谢:

SELECT
    User 
FROM
    [Member] m
WHERE 
    ((m.Gender = @Gender) or @Gender IS NULL)
    and ((DATEDIFF(hour,m.DOB,GETDATE())/8766) Between 
       CASE    
         WHEN @Age = 1 THEN (SELECT DATEDIFF(hour, m.DOB, GETDATE())/8766 WHERE (SELECT DATEDIFF(hour, m.DOB, GETDATE())/8766) between 15 and 18)
         WHEN @Age = 2 THEN (SELECT DATEDIFF(hour,m.DOB,GETDATE())/8766 WHERE (SELECT DATEDIFF(hour,m.DOB,GETDATE())/8766) between 19 and 25) 
       END) 

1 个答案:

答案 0 :(得分:4)

我认为这就是你所追求的(可能有一些多余的括号):

Select 
  [User]
From
  [Member] m
Where (
    (m.Gender = @Gender) or 
    @Gender Is Null
  ) And (
    (@Age = 1 And DateDiff(hour, m.Dob, GetDate())/8766 Between 15 and 18) Or
    (@Age = 2 And DateDiff(hour, m.Dob, GetDate())/8766 Between 19 and 25) 
  ) 

如果您有很多条款,可能更容易理解(假设有一个MemberID主键)

Select
  [User]
From
  [Member] m
    Inner Join (
      Select
        MemberID,
        DateDiff(hour, m.Dob, GetDate())/8766 As Years
      From
        [Member]
    ) As y
    On m.MemberID = y.MemberID
Where (
    (m.Gender = @Gender) or 
    @Gender Is Null
  ) And (
    (@Age = 1 And y.Year Between 15 and 18) Or
    (@Age = 2 And y.Year Between 19 and 25) 
  ) 

更好的是,您可以将范围添加到名为AgeRanges

的单独表格中
+-------+------------+----------+
| AgeID | StartYears | EndYears |
+-------+------------+----------+
|     1 |         15 |       18 |
|     2 |         19 |       25 |
|   ... |        ... |      ... |
+-------+------------+----------+

Select
  [User]
From
  [Member] m
    Inner Join
  [AgeRanges] a
    On DateDiff(hour, m.Dob, GetDate())/8766 Between a.StartYears and a.EndYears And
       a.AgeID = @Age

您还可以在成员表上为DateDiff(hour, m.Dob, GetDate())/8766计算列以简化操作(并在性能成为问题时使索引成为可能)。