我会尽力解释,但如果不清楚,请告诉我。英语不是我的第一语言。
我需要一些查询帮助,作为插入或不插入记录集的条件。
首先,我有一个数据库表 EmployeeProviders。
在其中一个存储过程中,我根据某些条件重新计算信用。在这种情况下,记录的数量是三个,但可能或多或少。
如果在重新计算后我得到与 EmployeeProviders 中相同的有效日期的数字或积分,我不需要插入这些值。EmployeeProviders 可能包含按生效日期分隔的每个员工的几组记录。
对我来说,困难在于构造一个查询,在这种情况下,它不是一个一个地检查记录,而是三个一组地检查记录。如果其中一条记录不匹配,我需要插入所有三条记录。如果它们都相同,我不插入任何记录。
declare @StartDate datetime, @employee_id int
select @StartDate = '2013-07-01', @employee_id = 3465
例如,这里是填充了值的 db 表
DECLARE @EmployeeProviders TABLE (
ident_id int IDENTITY,
employee_id int,
id int,
plan_id int,
credits decimal(18,5),
effective_date datetime
)
INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date)
VALUES (18753, 23, 0.00000, '2013-06-01')
INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date)
VALUES (3465, 18753, 15, 0.00000, '2013-06-01')
INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date)
VALUES (3465, 18753, 16, 60.00, '2013-06-01')
INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date)
VALUES (3465, 18753, 23, 0.00000, '2013-07-01')
INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date)
VALUES (3465, 18753, 15, 0.00000, '2013-07-01')
INSERT INTO @EmployeeProviders (employee_id, plan_id, id, credits, effective_date)
VALUES (3465, 18753, 16, 81.580, '2013-07-01')
SELECT * FROM @EmployeeProviders WHERE plan_id = 18753 and datediff(dd,effective_date,@StartDate) = 0
这是存储过程中的临时表。它在计算过程中得到更新
DECLARE @Providers TABLE (
id int,
plan_id int,
credits decimal(18,5)
)
INSERT INTO @Providers (plan_id, id, credits)
VALUES (18753, 23, 0.00000)
INSERT INTO @Providers (plan_id, id, credits)
VALUES (18753, 15, 0.00000)
INSERT INTO @Providers (plan_id, id, credits)
VALUES (18753, 16, 81.580)
SELECT * FROM @Providers
在此临时表中的所有更新量与 db 表 EmployeeProviders 中的所有更新量相同之后,我不需要插入新的记录集如何执行一个查询,该查询可以是 IF NOT EXISTS() 之类的条件,也可以只是执行 INSERT EmployeeProviders ()... SELECT ... FROM @Providers ,,, -- 如果值与 EmployeeProviders 中的值不同,该查询将返回我的 3 条记录集
另一种情况,@Providers.credits = 65,因为与 id = 16 的 EmployeeProviders.credits 相比,金额发生了变化。我将向 EmployeeProvider 表添加新的 3 条记录
DECLARE @Providers TABLE (
id int,
plan_id int,
credits decimal(18,5)
)
INSERT INTO @Providers (plan_id, id, credits)
VALUES (18753, 23, 0.00000)
INSERT INTO @Providers (plan_id, id, credits)
VALUES (18753, 15, 0.00000)
INSERT INTO @Providers (plan_id, id, credits)
VALUES (18753, 16, 65.00)
SELECT * FROM @Providers
先感谢您,
麦