码迷,mamicode.com
首页 > 其他好文 > 详细

利用Merge生成或更新新记录

时间:2016-06-23 15:50:00      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 -- =============================================
 2 -- Author:        <华仔>
 3 -- Create date: <2016,6,7>
 4 -- Description:    <鱼种统计>
 5 -- Update_QT_FishTypeCount 0,0,0,0 -- 测试可否正常运行
 6 -- 维护日志:
 7 --
 8 -- =============================================
 9 ALTER PROCEDURE [dbo].[Update_QT_FishTypeCount]
10 @RoomLevel INT,
11 @FishType INT,
12 @AppearNumber INT,
13 @CatchNumber INT
14 
15 AS
16 BEGIN
17     
18     SET NOCOUNT ON;
19 
20     BEGIN TRY--错误捕获
21     BEGIN TRAN; -- 开始事务
22 
23     WITH N AS(
24         SELECT @RoomLevel AS RoomLevel
25             ,CONVERT(CHAR(10),GETDATE(),23) AS CountDate
26             ,@FishType AS FishType
27             ,@AppearNumber AS AppearNumber
28             ,@CatchNumber AS CatchNumber
29     )
30     MERGE QT_FishTypeCount AS FTC
31     USING N ON N.CountDate = FTC.CountDate AND N.RoomLevel = FTC.RoomLevel AND N.FishType = FTC.FishType
32     WHEN NOT MATCHED 
33     THEN INSERT
34         (
35             [RoomLevel],
36             [CountDate],
37             [FishType],
38             [AppearNumber],
39             [CatchNumber]
40         )
41         VALUES
42         (
43             N.[RoomLevel],
44             N.[CountDate],
45             N.[FishType],
46             N.[AppearNumber],
47             N.[CatchNumber]
48         )
49     WHEN MATCHED 
50     THEN UPDATE SET [AppearNumber] = FTC.[AppearNumber] + @AppearNumber,[CatchNumber] = FTC.[CatchNumber] + @CatchNumber;
51 
52     COMMIT TRAN -- 执行无错误,提交事务
53     END TRY--错误捕获
54     BEGIN CATCH--错误捕获
55         ROLLBACK TRAN -- 执行出错,回滚事务
56         INSERT INTO [QPAccountsDB].[dbo].[QA_ErrorLog]
57             ([ErrorNumber]
58             ,[ErrorSeverity]
59             ,[ErrorState]
60             ,[ErrorProcedure]
61             ,[ErrorLine]
62             ,[ErrorMessage]
63             ,[ErrorTime])
64         SELECT ERROR_NUMBER()
65             ,ERROR_SEVERITY()
66             ,ERROR_STATE()
67             ,QPTreasureDB.dbo.Update_QT_FishTypeCount
68             ,ERROR_LINE()
69             ,ERROR_MESSAGE()
70             ,GETDATE()
71     END CATCH--错误捕获
72 END
View Code

 

利用Merge生成或更新新记录

标签:

原文地址:http://www.cnblogs.com/C-1989/p/5611040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!