"SQL" finds tables with unequal rows and self-increment identity values (that is, there are missing rows)

Source: Internet
Author: User

Original: "SQL" finds tables with unequal row count and self-increment identity value (that is, there are missing rows)

Environment:MSSQL ENT 2k8 R2

principle: traverse all user tables with self-increment columns, get the number of rows per table and write to the temporary table using the sp_spaceused procedure, and then use the Ident_current function to get the maximum identification value of the table, compare the two and return the result

IF object_id('tempdb: #TableRowCount','U') is  not NULL DROP TABLE#TableRowCountGOCREATE TABLE#TableRowCount (Name sysnamePRIMARY KEY, rowcntDECIMAL( One,0), ReservedVARCHAR( -), DataVARCHAR( -), index_sizeVARCHAR( -), UnusedVARCHAR( -))GODECLARECurcntalltablerowsCURSORLOCAL Fast_forward for        SELECTName fromSys.tablesWHERE ObjectProperty(object_id,'tablehasidentity')=1OPENcurcntalltablerowsDECLARE @TableNamesysnameFETCH NEXT  fromCurcntalltablerows into @TableName while @ @FETCH_STATUS=0BEGIN INSERT  into#TableRowCountEXECSys.sp_spaceused@TableName FETCH NEXT  fromCurcntalltablerows into @TableNameENDCLOSEcurcntalltablerowsdeallocatecurcntalltablerows/*since ident_current also returns 1 for empty tables, special handling is done*/ withCteA as (SELECTNAME,ROWCNT, CaseIdent_current (Name) when 1  ThenRowcntELSEIdent_current (Name)END  as 'Currid' from#TableRowCount)SELECTName,rowcnt,currid fromCteAWHERERowcnt<>Currid

Wenbi.

"SQL" finds tables with unequal rows and self-increment identity values (that is, there are missing rows)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.