SQL查询以查找重复项并比较最后两行

时间:2016-11-14 04:06:36

标签: sql sql-server tsql sql-server-2012

我们每周都会将数据库备份复制到特定位置。

已设置SQL Server代理作业以从该特定位置还原数据库。 如果由于某种原因,备份复制过程无效,则不会替换现有副本。 SQL Server代理作业正在恢复上周的备份副本。

我正在运行此查询以查明“Backup_set_id”是否已更改:

select * 
from [msdb].[dbo].[restorehistory]
where destination_database_name = 'DB Name'
order by restore_history_id desc

这将填充Backup_set_id和其他东西。如果Backup_set_id的最后两个值没有改变,我知道复制过程不起作用。

请您帮我用SQL脚本每周设置一个SQL代理作业来验证Backup_set_id。如果Backup_set_的最后两行没有改变,我可以收到电子邮件通知吗?

非常感谢。

2 个答案:

答案 0 :(得分:0)

此查询会计算restore_history_id ID列中的唯一值。

如果此查询返回任何行,则表示它是重复的restore_history_id值。

您可以使用自己的应用程序自动查询此信息,并使用结果确定是否发送电子邮件。

SELECT restore_history_id, COUNT(restore_history_id) FROM [msdb].[dbo].[restorehistory]
WHERE destination_database_name = 'DB Name'
GROUP BY restore_history_id
HAVING COUNT(restore_history_id) > 1

答案 1 :(得分:0)

--compare the two ID's You may need to change what you are ordering by to keep the data in order

declare @ct int
set @ct = 
    (select sum(CT) from
    (select top 2 case when lead(backup_set_id) over (order by restore_history_id) = backup_set_id then 1 else 0 end as CT
    from 
    restorehistory))

IF @ct = 1 --this means the last two IDs were the same

    BEGIN
        EXEC msdb.dbo.sp_send_dbmail 
            @profile_name = 'Your Profile Name',
            @recipients = 'you@domain.com',
            @subject = 'Status Update',
            @body = 'The process did not work'

            --or just raise an error

        RAISERROR('There are duplicate records',16,1)
    END
ELSE
    BEGIN
        --do something else... or don't
    END