8

使用 Microsoft SQL Server Management Studio 2008。我做了一个简单的事务:

BEGIN TRAN

SELECT ko.ID, os.ID AS ID2
FROM table_a AS ko
JOIN table_b AS os ON os.ID=ko.ID
WHERE (ko.the_date IS NOT NULL AND os.the_date IS NULL);

UPDATE table_b SET the_date=ko.the_date
FROM table_a AS ko
JOIN table_b AS os ON os.ID=ko.ID
WHERE (ko.the_date IS NOT NULL AND os.the_date IS NULL);

SELECT ko.ID, os.ID AS ID2
FROM table_a AS ko
JOIN table_b AS os ON os.ID=ko.ID
WHERE (ko.the_date IS NOT NULL AND os.the_date IS NULL);


ROLLBACK

所以 SELECT 和 UPDATE 应该是一样的。结果应该返回 0 行。但是 UPDATE 影响的行比 SELECT 从 DB 中获得的少:

(61 行受影响)

(60 行受影响)

(0 行受影响)

我在这里想念什么?

4

2 回答 2

2

我怀疑最可能的原因是您的示例中的 Table_a 有一行带有重复 ID - 这种情况下您的第一个连接中会出现一个额外的行select,但update唯一处理 Table_b 中的行,所以您的重复行无所谓。这句话应该给你罪魁祸首:

SELECT ko.ID
FROM table_a AS ko
JOIN table_b AS os ON os.ID=ko.ID
WHERE (ko.the_date IS NOT NULL AND os.the_date IS NULL)
GROUP BY ko.ID
HAVING COUNT(*) > 1
于 2010-10-05T15:36:40.890 回答
0

UPDATE...FROM 没有检测到像这样的歧义:

CREATE TABLE dbo.source
    (
      id INT NOT NULL ,
      SomeNumber INT
    )
GO
CREATE TABLE dbo.target
    (
      id INT NOT NULL
             PRIMARY KEY ,
      SomeNumber INT
    )
GO
INSERT  INTO dbo.source
        ( id, SomeNumber )
        SELECT  1 ,
                2
        UNION ALL
        SELECT  1 ,
                3

INSERT  INTO dbo.target
        ( id, SomeNumber )
        SELECT  1 ,
                0

UPDATE  dbo.TARGET
SET     SomeNumber = s.SomeNumber
FROM    dbo.source AS s
        JOIN dbo.TARGET AS t ON s.id = t.id

目标表中的行在源中有两个匹配项,我们无法提前知道哪个值最终会更新目标。

于 2010-10-05T14:20:17.463 回答