首页 > 代码库 > 【SQL】找出行数与自增标识值不相等的表(即有缺行)

【SQL】找出行数与自增标识值不相等的表(即有缺行)

原文:【SQL】找出行数与自增标识值不相等的表(即有缺行)

环境:mssql ent 2k8 r2

原理:遍历所有含自增列的用户表,用sp_spaceused过程分别获取每张表的行数并写入临时表,然后使用IDENT_CURRENT函数获取表的最大标识值,比较二者并返回结果

IF OBJECT_ID(tempdb..#TableRowCount,U) IS NOT NULL DROP TABLE #TableRowCountGOCREATE TABLE #TableRowCount (Name sysname PRIMARY KEY, RowCnt DECIMAL(11,0), Reserved VARCHAR(18), Data VARCHAR(18), Index_Size VARCHAR(18), Unused VARCHAR(18))GODECLARE curCntAllTableRows CURSOR LOCAL FAST_FORWARD FOR        SELECT name FROM sys.tables WHERE OBJECTPROPERTY(object_id,TableHasIdentity)=1OPEN curCntAllTableRowsDECLARE @TableName sysnameFETCH NEXT FROM curCntAllTableRows INTO @TableNameWHILE @@FETCH_STATUS=0BEGIN INSERT INTO #TableRowCount EXEC sys.sp_spaceused @TableName FETCH NEXT FROM curCntAllTableRows INTO @TableNameENDCLOSE curCntAllTableRowsDEALLOCATE curCntAllTableRows/*由于IDENT_CURRENT对于空表也会返回1,所以做特别处理*/WITH cteA AS (SELECT Name,RowCnt,CASE IDENT_CURRENT(Name) WHEN 1 THEN RowCnt ELSE IDENT_CURRENT(Name) END AS CurrIDFROM #TableRowCount)SELECT Name,RowCnt,CurrIDFROM cteAWHERE RowCnt<>CurrID

文毕。

 

【SQL】找出行数与自增标识值不相等的表(即有缺行)