SQL Server 2008 R2 Merge正在删除错误的数据集

时间:2012-10-09 23:24:53

标签: sql-server-2008 tsql

我有表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)
)

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

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代码有什么问题导致它影响网页传递更新的{{1}}以外的项目?

2 个答案:

答案 0 :(得分: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
;

答案 1 :(得分: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的帮助下收集的。