2

几个星期以来,我一直在寻找解决方案,我只是想问一下。我必须合并两个表,但我不能依赖 id(pk),因为它会自动递增并且绝对不会相同。在这里,如果我的 SP:

BEGIN
            MERGE dbo.Publication AS Target
            USING (SELECT id, parent_publication_id, name, date_created, last_updated
                    FROM dbo.ImportPublication
                    where id = @publicationid
                    )
            AS Source
            ON (Target.name = Source.name and Target.parent_publication_id = Source.    parent_publication_id)
            WHEN MATCHED THEN
            UPDATE SET 
                Target.name = Source.name, Target.parent_publication_id = Source.parent_publication_id, Target.date_created = Source.date_created, Target.last_updated = Source.last_updated
            WHEN NOT MATCHED BY TARGET THEN
            INSERT (name, parent_publication_id, date_created, last_updated )
            VALUES ( Source.name, Source.parent_publication_id, Source.date_created, Source.last_updated);
            DECLARE @pubId INT =  SCOPE_IDENTITY()
            if(@pubId != null or @pubId !='')
            begin
                UPDATE dbo.ImportFixedSize
                SET publication_id = @pubId
                where publication_id = @publicationId
            end
            else
                begin
                    set @pubId = ( select Id from Publication where name = ( select name from ImportPublication where id = @publicationid))
                    UPDATE dbo.ImportFixedSize
                    SET publication_id = @pubId
                    where publication_id = @publicationId
                end

我在标题中收到错误。可能是什么原因?我知道事实上没有两行具有相同的名称和publication_group_id

4

1 回答 1

0

以下是我可以看到的可能导致这种情况的潜在代码异味 - 如果没有看到确切的故障点,就不可能知道。

1、

UPDATE SET 
            Target.name = Source.name, Target.parent_publication_id = Source.parent_publication_id

你为什么做这个?如果它已经匹配,那么我们不会尝试更改它匹配的内容。

2、

if(@pubId != null or @pubId !='')

比较空值时,您必须使用@value IS NULL 或@value IS NOT NULL。这是证明:

    declare @test int = 1
if (@test != null)
    select 1
if (@test is null)
    select 2
if (@test is not null)
    select 3
于 2013-07-24T16:46:15.783 回答