sql 存在即更新不存在则插入的另一种写法
CREATE PROCEDURE [dbo].[P_ExtensionLinkCount] @BeginDate date AS BEGIN declare @Now date, @Yesterday date, -- 昨天 @IsRefresh int -- 是否更新某字段 1更新 0不更新 set @Now=GETDATE() set @Yesterday=DATEADD(day,-1,@Now) set @IsRefresh=0 if @BeginDate = @Now or @BeginDate = @Yesterday begin set @IsRefresh=1 end -- 更新指定日期(@BeginDate)数据 ;with c1 as( -- 此处省略复杂逻辑 select * from t1 where State=1 ) MERGE INTO t2 as target USING c1 as source ON (target.id=source.id and target.date=source.date) WHEN MATCHED THEN -- 存在则更新 UPDATE -- 如果是当天 则更新字段 否则不更新某字段 SET target.c1= case when @IsRefresh=1 then source.c1 else target.c1 end, target.c2= case when @IsRefresh=1 then source.c2 else target.c2 end, target.c3= source.c3, target.c4= source.c4, target.c5= source.c5, target.c5= source.c6, target.c7= source.c7, target.c8=source.c8 WHEN NOT MATCHED THEN -- 不存在则插入 INSERT (c1,c2,c3,c4,c5,c6,c7,c8,c9,c10) VALUES (c1,c2,c3,c4,c5,c6,c7,c8,c9,c10); END
- 仅记录sql结构与写法,列名与表名已经抹掉;