SQL Server合并使用过滤器删除

时间:2014-10-01 13:35:54

标签: sql sql-server merge

我使用合并进行插入或删除,我不知道应该如何看。我有一个映射表,将分类法映射到支持的语言。该表看起来像:

TaxonomyLanguageID(PK) | TaxonomyID(FK) | LanguageID(FK)

我想要做的是将临时表与上面的表合并,其中临时表将包含分类法支持的语言列表。例如:

TaxonomyID|LanguageID

456,        2

456,        3

456,        9

我尝试的内容看起来像这样(选择用于测试,稍后这将是临时表):

MERGE dbo.TaxonomyLanguages as t
using (SELECT 5395  as TaxonomyID, 2 as LanguageID) as s
ON (s.TaxonomyID=T.TaxonomyID AND s.LanguageID=t.LanguageID)
WHEN NOT MATCHED BY TARGET THEN
    INSERT(TaxonomyID,LanguageID) VALUES(S.TaxonomyID,s.LanguageID)
WHEN NOT MATCHED BY SOURCE AND T.TaxonomyID=s.TaxonomyID
    THEN DELETE;

我想要做的是插入如果它不匹配,如果不匹配则删除,但只删除目标中与源中找到的taxonomyID匹配的那些行。

但我得到一个“当'与源'不匹配的子句'错误时,只允许目标列。

关于如何解决这个问题(或者应该如何解决)的任何想法?

我正在寻找的例子。如果我有一个像

的来源
TaxonomyID|LanguageID

4000,      2

4000,      3

和目标一样:

TaxonomyLanguageID|TaxonomyID|LanguageID

1,                  3000       2

2,                  4000       1

3,                  4000       2

最终结果将是:

TaxonomyLanguageID|TaxonomyID|LanguageID

1,                 3000       2

3,                 4000       2

4,                 4000       3

1 个答案:

答案 0 :(得分:1)

由于关键字段的数量不同,您必须将其分为两遍。

Select 456 as TaxonomyID, 2 as LanguageID
  into TaxonomyLanguages

INSERT INTO [dbo].[TaxonomyLanguages]
           ([TaxonomyID]
           ,[LanguageID])
     VALUES
           (456, 3)
           ,(456, 9)
GO

select *
from [TaxonomyLanguages]


MERGE dbo.TaxonomyLanguages as t
using (SELECT 5395  as TaxonomyID, 2 as LanguageID) as s
ON (s.TaxonomyID=T.TaxonomyID AND s.LanguageID=t.LanguageID)
WHEN NOT MATCHED BY TARGET THEN
    INSERT(TaxonomyID,LanguageID) VALUES(S.TaxonomyID,s.LanguageID);


MERGE dbo.TaxonomyLanguages as t
using (SELECT 5395  as TaxonomyID, 2 as LanguageID) as s
ON (s.TaxonomyID=T.TaxonomyID)
WHEN NOT MATCHED BY SOURCE 
    THEN DELETE;

select *
from [TaxonomyLanguages]

根据评论,更改第二次合并:

MERGE dbo.TaxonomyLanguages as t
using (SELECT 456  as TaxonomyID, 3 as LanguageID) as s
ON (s.TaxonomyID=T.TaxonomyID)
WHEN  MATCHED 
  and (s.LanguageID <> T.LanguageID)
    THEN DELETE;