我的桌子只有两个字段,如
Act nvarchar(50)
Cnt int
并且有存储过程来更新/插入记录,如果有新的Act将cnt设置为1,如果有一个Act已经增加了cnt + 1。存储过程看起来像
ALTER PROCEDURE [dbo].[usp_INSU]
@act_TT AS act_TT READONLY
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION;
MERGE dbo.[c_Act] prj
USING @act_TT tt
ON prj.Act = tt.Act
WHEN MATCHED THEN UPDATE SET prj.Cnt=prj.Cnt+1
WHEN NOT MATCHED THEN INSERT (Act,Cnt)
VALUES (tt.Act, 1);
select * from dbo.[c_Act] ca Join @act_TT TT On ca.Act = TT.Act;
COMMIT TRANSACTION;
现在我需要在表格中添加一个名为year的字段,该字段应该只存储当前年份。我不知道如何存储年份,我知道Datetime数据类型存储所有dd,mm,yyyy和时间。此外,如果年份发生变化,无论法案如何,我们都需要将Cnt重置为1。在这里,我不确定年份字段的数据类型以及如何检查年份并重置计数器
答案 0 :(得分:3)
我会使用INT
年份并以YYYY
的格式存储,以获取当前年份SELECT YEAR(GETDATE())
。您的合并声明看起来像......
MERGE dbo.[c_Act] prj
USING @act_TT tt ON prj.Act = tt.Act
WHEN MATCHED THEN UPDATE
SET prj.Cnt = prj.Cnt+1
,prj.YearCol = YEAR(GETDATE())
WHEN NOT MATCHED THEN
INSERT (Act , Cnt , YearCol )
VALUES (tt.Act, 1 , YEAR(GETDATE()) );
答案 1 :(得分:1)
我们如何检查下一年是否接下来然后再将cnt重置为1
MERGE dbo.[c_Act] prj
USING @act_TT tt ON prj.Act = tt.Act
WHEN MATCHED AND prj.YearCol = YEAR(GETDATE()) - 1 THEN UPDATE
SET prj.Cnt = 1
,prj.YearCol = YEAR(GETDATE())
WHEN MATCHED AND prj.YearCol != YEAR(GETDATE()) - 1 THEN UPDATE
SET prj.Cnt = prj.Cnt+1
,prj.YearCol = YEAR(GETDATE())
WHEN NOT MATCHED THEN
INSERT (Act , Cnt , YearCol )
VALUES (tt.Act, 1 , YEAR(GETDATE()) );
OR
MERGE dbo.[c_Act] prj
USING @act_TT tt ON prj.Act = tt.Act
WHEN MATCHED THEN UPDATE
SET prj.Cnt = CASE WHEN prj.YearCol = YEAR(GETDATE()) - 1 THEN 1 ELSE prj.Cnt+1 END
,prj.YearCol = YEAR(GETDATE())
WHEN NOT MATCHED THEN
INSERT (Act , Cnt , YearCol )
VALUES (tt.Act, 1 , YEAR(GETDATE()) );