2

我有桌子tblCollectionGameList

CREATE TABLE dbo.tblCollectionGameList
(
    ListID smallint IDENTITY(0,1) NOT NULL,
    CollectionID smallint NOT NULL,
    IncludedSectionID smallint NOT NULL,
    CONSTRAINT PK_CollectionGameList_ListID PRIMARY KEY CLUSTERED (ListID ASC),
    CONSTRAINT FK_CollectionGameList_SectionInfo FOREIGN KEY (CollectionID) REFERENCES dbo.tblSectionInfo (SectionID),
    CONSTRAINT FK_CollectionGameList_SectionInfo2 FOREIGN KEY (IncludedSectionID) REFERENCES dbo.tblSectionInfo (SectionID)
)

MERGE从我的网站传递一组 XML 值后,我运行以下命令

SELECT 
   CAST(colx.query('data(CollectionID) ') AS varchar) AS CollectionID,
   CAST(colx.query('data(IncludedSectionID) ') AS varchar) AS IncludedSectionID
INTO #TEMPtblCollectionGameList
FROM @XMLTable.nodes('DocumentElement/XMLTable') AS Tabx(Colx)

MERGE dbo.tblCollectionGameList AS t
USING #TEMPtblCollectionGameList AS s
ON (t.CollectionID = s.CollectionID AND t.IncludedSectionID= s.IncludedSectionID)
WHEN NOT MATCHED BY TARGET
    THEN
        INSERT (CollectionID, IncludedSectionID)
        VALUES (s.CollectionID, s.IncludedSectionID)
WHEN NOT MATCHED BY SOURCE
    THEN
        DELETE
;

这是行不通的。如果我的表中有一组现有数据:

ListID  CollectionID    IncludedSectionID
34      86              0
35      86              1

我尝试从我的网页放置新数据以用于不同的集合,CollecitonID它正在删除旧数据并将新数据放入:

ListID  CollectionID    IncludedSectionID
38      92              10
39      92              11

我的MERGE代码有什么问题导致它影响CollectionID网页正在传递的更新之外的项目?

4

2 回答 2

0

您可以向WHEN NOT MATCHED BY SOURCE子句添加条件。

merge dbo.tblCollectionGameList as T
using #TEMPtblCollectionGameList as S
on S.CollectionID = T.CollectionID and
   S.IncludedSectionID = T.IncludedSectionID
when not matched by target
  then
    insert(CollectionID, IncludedSectionID)
      values(S.CollectionID, S.IncludedSectionID)
when not matched by source and 
     T.CollectionID in (select S.CollectionID
                        from #TEMPtblCollectionGameList as S)
  then
    delete
;
于 2012-10-10T13:06:51.580 回答
0

解决方案是添加以下内容:

WITH tblCGL AS
(
    SELECT ListID, CollectionID, IncludedSectionID
    FROM dbo.tblCollectionGameList AS CGL
    WHERE EXISTS
    (
        SELECT CollectionID, IncludedSectionID
        FROM #TEMPtblCollectionGameList AS TempCGL
        WHERE CGL.CollectionID = TempCGL.CollectionID
    )
)

这是在 SQLteam.com 的帮助下收集的。

于 2012-10-10T21:29:02.377 回答