3

我正在处理的应用程序调用这样的 SP:

exec CreateChildRecord @ParentID = 123, @ChildID = 124

SP 需要将父记录中除 ID 外的所有字段复制到子记录中。子记录当前可能存在也可能不存在。

我需要的是如下所示:

UPDATE [Table] AS [Table1] SET (data1, data2) = (
   SELECT [Table2].[data1], [Table2].[data2] 
      FROM [Table] AS [Table2] 
      WHERE [Table2.ID] = @ParentID)
   WHERE [Table1].[ID] = @ChildID
IF @@ROWCOUNT = 0
INSERT INTO [TABLE] (id, data1, data2) 
   (SELECT @ChildID, data1, data2 
      FROM [TABLE] 
      WHERE id = @ParentID)

我已经尝试了上述的各种组合,但没有效果。任何人都可以帮忙吗?

4

3 回答 3

3

如果你可以使用merge语句:

merge [Table] as T
using (
    select @ChildID as ID, data1, data2
    from [Table]
    where ID = @ParentID
) as P on P.ID = T.ID
when matched then
    update set
        data1 = P.data1,
        data2 = P.data2
when not matched then
    insert (ID, data1, data2)
    values (P.ID, P.data1, P.data2);

如果您不能使用merge

if exists (select * from [Table] where ID = @ChildID)
    update c set
        data1 = p.data1, 
        data2 = p.data2
    from [Table] as c cross join [Table] as p
    where c.ID = @ChildID and p.ID = @ParentID
else
    insert into [Table] (ID, data1, data2)
    select @ChildID, data1, data2
    from [Table]
    where ID = @ParentID

sql fiddle demo

于 2013-10-11T11:49:53.187 回答
1

根据您使用的 SQL Server 版本(2008+),您可以使用MERGE(Transact-SQL)

根据与源表连接的结果对目标表执行插入、更新或删除操作。例如,您可以通过根据在另一个表中发现的差异在一个表中插入、更新或删除行来同步两个表。

SQL 小提琴演示

于 2013-10-11T11:42:58.027 回答
1

您可以使用:

IF EXISTS (SELECT * FROM Table2 WHERE Table2.ParentID = @ParentID)

    UPDATE Table2 
    SET
       Table2.data1 = Table1.data1, Table2.data2 = Table1.data2
    FROM Table1
    WHERE Table1.ID = @ParentID

ELSE

   INSERT INTO Table2 (ParentID, data1, data2)
   SELECT @ParentID, Table1.data1, Table1.data2
   FROM Table1
   WHERE Table1.ID = @ParentID
于 2013-10-11T11:50:00.297 回答