如何根据select中的两个条件更新表中的日期

时间:2017-07-06 19:27:14

标签: sql sql-server

我需要根据是否从其他表中的select返回userID和planName来更新一个表中的日期。 像

这样的东西
UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)

4 个答案:

答案 0 :(得分:1)

最简单的方法是在UPDATE语句中连接这两个表。

尝试以下方法:

UPDATE [Table A] 
SET DATE = GETDATE()
FROM [Table A] a
INNER JOIN [Table B] b on a.userid = b.userid and a.planName = b.planName

答案 1 :(得分:0)

我认为这就是你要找的东西:

UPDATE A
  SET
      A.DATE = GETDATE()
FROM TableA AS A
WHERE EXISTS
(
    SELECT 1
    FROM TableB AS B
    WHERE B.userid = A.userid
          AND B.planName = A.planName
);

这将更新表A中具有表B中存在的userid和planName的确切组合的所有行

所以如果表A有以下内容:

userid planName 
1       A
2       A
1       B

和表B具有以下

userid planName 
1       A 
1       B

它只会更新表A中的以下内容:

userid planName 
1       A 
1       B

答案 2 :(得分:0)

看看这是否有帮助......

-- some test data...
IF OBJECT_ID('tempdb..#TableA', 'U') IS NOT NULL 
DROP TABLE #TableA;

CREATE TABLE #TableA (
    UserID INT NOT NULL,
    PlanName VARCHAR(5) NOT NULL,
    SomeDate DATE NULL,
    PRIMARY KEY CLUSTERED (UserID)
    );

IF OBJECT_ID('tempdb..#TableB', 'U') IS NOT NULL 
DROP TABLE #TableB;

CREATE TABLE #TableB (
    UserID INT NOT NULL,
    PlanName VARCHAR(5) NOT NULL,
    PRIMARY KEY CLUSTERED (UserID, PlanName)
    );

INSERT #TableA (UserID, PlanName) VALUES
    (1, 'aaa'), (2, 'aab'), (3, 'abb'),
    (4, 'aaa'), (5, 'aab'), (6, 'ccc');

INSERT #TableB (UserID, PlanName) VALUES
    (1, 'aaa'), (1, 'abb'), (1, 'bbb'),
    (2, 'aaa'), (2, 'abb'), (2, 'bbb'),
    (3, 'aaa'), (3, 'abb'), (3, 'bbb'),
    (4, 'aaa'), (4, 'abb'), (4, 'bbb'),
    (5, 'aaa'), (5, 'abb'), (5, 'bbb'),
    (6, 'aaa'), (6, 'abb'), (6, 'bbb');

--=========================================

-- check initial values...
SELECT * FROM #TableA ta;
SELECT * FROM #TableB tb;

-- written as a SELECT...
SELECT 
    *
FROM
    #TableA ta
WHERE 
    EXISTS (SELECT 1 FROM #TableB tb WHERE ta.UserID = tb.UserID AND ta.PlanName = tb.PlanName);

    -- written as an UPDATE...
UPDATE ta SET 
    ta.SomeDate = GETDATE()
FROM
    #TableA ta
WHERE 
    EXISTS (SELECT 1 FROM #TableB tb WHERE ta.UserID = tb.UserID AND ta.PlanName = tb.PlanName);

-- check updated values...
SELECT * FROM #TableA ta;

答案 3 :(得分:0)

能够得到它:

WITH CTE (userid, planName)
AS (SELECT userid, planName From Table B) 
UPDATE A
SET DATE = GETDATE()
FROM Table A
JOIN CTE B
ON B.userid = A.userid AND B.planName = A.planName