Skip to content

Instantly share code, notes, and snippets.

@edward-hsu-1994
Created July 15, 2015 04:13
Show Gist options
  • Save edward-hsu-1994/1407a752833ff876bba8 to your computer and use it in GitHub Desktop.
Save edward-hsu-1994/1407a752833ff876bba8 to your computer and use it in GitHub Desktop.
Insert Or Update
DECLARE @UpdateTable table(--暫存表,用以暫時儲存要更新或新增的目標資料
[Id] int,
[Name] nvarchar(16),
[Count] int
)
insert @UpdateTable select Min([Id]),Min([Name]),Sum([Count]) from (--將要更新的資料寫入暫存表
select * from [test].[TableA]
union all
select * from [test].[TableB]
) as TempA group by [Id]
while(exists(select * from @UpdateTable))BEGIN--將更新表中的資料逐筆讀出
DECLARE @Id int,@Count int;
select top 1 @Id = [Id],@Count = [Count] from @UpdateTable;--讀出資料
if(exists(select * from [test].[TableB] where [Id] = @Id))
update [test].[TableB] set [Count] = @Count where [Id] = @Id;--更新TableB
else
insert [test].[TableB] select top 1 * from @UpdateTable--插入一筆新資料
delete @UpdateTable where [Id] = @Id;--已經更新過的資料刪除
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment