我正在处理的应用程序调用这样的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)
我尝试了以上各种组合,没有效果。有人可以帮忙吗?
答案 0 :(得分: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 强>
答案 1 :(得分:1)
根据您使用的SQL Server版本(2008+),您可以使用MERGE (Transact-SQL)
基于目标表执行插入,更新或删除操作 关于与源表的连接的结果。例如,你可以 通过在一个表中插入,更新或删除行来同步两个表 表基于另一个表中的差异。
答案 2 :(得分: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