每当在数据库中插入或更新数据时,我都会尝试更新我的控制表。为此,我创建了一个存储过程,它将获取表名(@TableName)、插入的行数(@InsertCount)和更新的行数(@UpdateCount)
我试图实现 3 级的嵌套 ifs,但存储过程不起作用。
谁能帮我理解存储过程可能有什么问题?
/*
A row is present in the control table @InsertCount is greater than 0 @UpdateCount is greater than 0 Action
(True/False) False False No action needs to be performed
False False True Insert row in control table and set LastLoadDateTime and DWUpdateDate to current time
False True False Insert row in control table and set LastLoadDateTime and DWInsertDate to current time
False True True Insert row in control table and set LastLoadDateTime, DWUpdateDate, and DWInsertDate to current time
True False True Update row in control table and set LastLoadDateTime and DWUpdateDate to current time
True True False Update row in control table and set LastLoadDateTime and DWInsertDate to current time
True True True Update row in control table and set LastLoadDateTime, DWUpdateDate, and DWInsertDate to current time
*/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [schema].[StoredProcedure](@TableName nvarchar(50), @InsertCount bigint, @UpdateCount bigint)
as
DECLARE @JobEndTime datetime;
DECLARE @IsPresent bit;
SET @JobEndTime = GETDATE();
SET @IsPresent = (
select top 1 COUNT(*)
from schema.Control_Table
where TableName = @TableName
)
if(@IsPresent = 0)
BEGIN
if(@InsertCount <> 0)
BEGIN
if(@UpdateCount <> 0)
insert schema.Control_Table(TableName, LastLoadDateTime, DWInsertDate, DWUpdateDate)
values (@TableName, @JobEndTime, @JobEndTime, @JobEndTime)
else
insert schema.Control_Table(TableName, LastLoadDateTime, DWInsertDate)
values (@TableName, @JobEndTime, @JobEndTime)
END
else
BEGIN
if(@UpdateCount <> 0)
insert schema.Control_Table(TableName, LastLoadDateTime, DWUpdateDate)
values (@TableName, @JobEndTime, @JobEndTime)
END
END
else
BEGIN
if(@InsertCount <> 0)
BEGIN
if(@UpdateCount <> 0)
update schema.Control_Table
set
LastLoadDateTime = @JobEndTime,
DWUpdateDate = @JobEndTime,
DWInsertDate = @JobEndTime
where TableName = @TableName
else
update schema.Control_Table
set
LastLoadDateTime = @JobEndTime,
DWInsertDate = @JobEndTime
where TableName = @TableName
END
else
BEGIN
if(@UpdateCount <> 0)
update schema.Control_Table
set
LastLoadDateTime = @JobEndTime,
DWUpdateDate = @JobEndTime
where TableName = @TableName
END
END
您可以使用CTE和MERGE语句来简化存储过程,以避免需要使用嵌套的 IF 语句。有关工作示例,请参阅此db<>fiddle 。
这是存储过程代码:
其工作方式是 CTE 创建一个伪表,其中包含一行,其中包含表名称、最后加载日期时间、插入日期时间和更新日期时间的列。如果插入日期列的@InsertCount > 0,CTE 使用IIF 子句返回GETDATE(),使用@UpdateCount 的更新日期列也是如此。
然后将此数据用作 MERGE 语句的源,该语句基本上执行 UPSERT。如果为提供的表名找到现有行,则更新日期列,如果未找到现有行,则插入新行。
更新现有行的日期列的逻辑如下: