Sql 使用新的用户列表更新现有表,而不是每天运行整个查询来替换表?
我正在SQL Server中每天更新用户列表的作业中运行查询。 下面的查询每天都在运行以更新数据Sql 使用新的用户列表更新现有表,而不是每天运行整个查询来替换表?,sql,sql-server,Sql,Sql Server,我正在SQL Server中每天更新用户列表的作业中运行查询。 下面的查询每天都在运行以更新数据 if object_id('report.dbo.data') is not null drop table report.dbo.data SELECT UserID, date into report.dbo.data from data a where date >= '2019-01-01' and date < getdate() 此查询的目标是每天更新用户
if object_id('report.dbo.data') is not null
drop table report.dbo.data
SELECT
UserID,
date
into report.dbo.data
from data a
where date >= '2019-01-01'
and date < getdate()
此查询的目标是每天更新用户列表。这里的问题是,每天运行它需要更长的时间
例如,我可能已经拥有2019年4月20日之前的数据。因为我每天都运行它,所以数据从2019年1月1日到2019年4月25日再次运行,而不仅仅是从2019年4月20日到2019年4月25日使用新的用户名更新
您能帮我提供一个示例代码,用新数据更新report.dbo.data,而不是运行整个代码来刷新所有数据吗?而不是将日期硬编码为“2019-01-01”从数据传递maxdate
您的代码删除并重新创建整个表,而不仅仅是它的数据内容。让我们创建一个空表report.dbo.data(如果它不存在),并只追加新数据
if object_id('report.dbo.data') is null
SELECT UserID, date into report.dbo.data from data a where 1=0 -- create empty table if needed
insert into report.dbo.data(UserID, date) -- append new data
(SELECT UserID, date from data a where date > (select max(date) from data) and date < getdate())
如果需要即时更新,请切换到基于触发器的解决方案。放弃作业并对插入report.dbo.data的表数据创建触发器。它不仅速度更快,而且总是100%最新的,在任何给定的时间,而不是一天一次
if object_id('report.dbo.data') is null
SELECT UserID, date into report.dbo.data from data a where 1=0 -- create empty table if needed
insert into report.dbo.data(UserID, date) -- append new data
(SELECT UserID, date from data a where date > (select max(date) from data) and date < getdate())