想要在条件上执行条款

时间:2014-07-28 18:14:47

标签: sql

我认为我过于复杂了,但我有一个用户表和一个程序表。用户与一个或多个程序绑定,我想锁定所有不属于01-01-2014到期日期的任何程序的用户:

TABLE Users
UserId INT PKEY
Locked BIT

TABLE Programs
ProgramId INT PKEY
UserId INT FKEY => Users.UserId
ExpirationDate DATETIME

我试图做这样的事情:

UPDATE u
SET u.Locked = 1
FROM Users u
JOIN Programs p ON u.UserId = p.ProgramId
HAVING COUNT(p.ExpirationDate >= '01-01-2014') = 0
GROUP BY u.UserId

但显然HAVING条款格式不正确。我认为这很简单,我只是忽略了,但我怎样才能更新没有程序在今年1月1日之后到期的用户?最好不使用子选择。

1 个答案:

答案 0 :(得分:0)

UPDATE users
SET Locked = 1
FROM Users
WHERE userid NOT IN (
        SELECT userid
        FROM Users u
        INNER JOIN Programs p ON u.UserId = p.ProgramId
        WHERE p.ExpirationDate >= '01-01-2014'
        )

或者使用cte尝试下面的

; WITH ToUpdate
AS (
    SELECT Userid
        ,locked
    FROM Users u
    LEFT JOIN Programs p ON u.UserId = p.ProgramId
    GROUP BY u.UserId, u.locked
    HAVING ISNULL(SUM(CASE 
                WHEN p.ExpirationDate >= '01-01-2014'
                    THEN 1
                ELSE 0
                END),0) = 0

    )
UPDATE ToUpdate
SET Locked = 1