我正在尝试使用查询来检索服务器上每个数据库的最新备份的详细信息。
查询是:
WITH CTE_max as
(
SELECT bs2.database_name,MAX(bs2.backup_start_date) as maxdate
FROM msdb.dbo.backupset bs2 GROUP BY database_name
)
SELECT DISTINCT
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,
bs1.database_name,
bs1.backup_start_date,
bs1.backup_finish_date,
FROM msdb.dbo.backupset bs1
INNER JOIN CTE_max CTE ON bs1.backup_start_date = CTE.maxdate
ORDER BY
bs1.database_name,
bs1.backup_start_date desc
当我运行它时,它只返回服务器上大约一半数据库的详细信息。我尝试在主查询中用子查询替换CTE,并在加入之前将日期转换为varchars,但结果是相同的。
当我自己运行CTE查询时,它会返回所有数据库的结果,但只要它在主查询中加入,大约一半的结果就会消失。当桌子与自身联系时,我有点感到困惑。
非常感谢任何建议!
答案 0 :(得分:0)
尝试这样,在连接条件下添加DBName可以更好地发布一些样本数据进行测试。
WITH CTE_max as
(
SELECT bs2.database_name,MAX(bs2.backup_start_date) as maxdate
FROM msdb.dbo.backupset bs2 GROUP BY database_name
)
SELECT CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,
bs1.database_name,
bs1.backup_start_date,
bs1.backup_finish_date
FROM msdb.dbo.backupset bs1
INNER JOIN CTE_max CTE ON bs1.backup_start_date = CTE.maxdate
AND bs1.database_name=CTE.database_name
ORDER BY
bs1.database_name,
bs1.backup_start_date desc