SlideShare une entreprise Scribd logo
1  sur  6
Télécharger pour lire hors ligne
How do I... Reseed a SQL Server identity column? | TechRepublic



   ZDNet Asia    SmartPlanet    TechRepublic                                                                                     Log In    Join TechRepublic    FAQ       Go Pro!




                                                    Blogs     Downloads       Newsletters       Galleries     Q&A     Discussions         News
                                               Research Library


     IT Management             Development          IT Support       Data Center         Networks         Security




     Home / Blogs / The Enterprise Cloud                                                  Follow this blog:

     The Enterprise Cloud


     How do I... Reseed a SQL
     Server identity column?
     By Susan Harkins
     July 15, 2008, 11:53 AM PDT

     Microsoft SQL Server’s identity column generates sequential values for new
     records using a seed value. The term seed refers to the internal value SQL
     Server uses to generate the next value in the sequence. By default, an identity
     column’s first value is 1 and each new value increments by one (1, 2, 3, 4, and
     so on).

     You can control the column’s first and subsequent values, by specifying those values when you
     create the column. For instance, you might want to begin with a purchase order number of 1001                          Data Masking
     rather than 1.
                                                                                                                            Software
     Once the table’s in production you can reset, or reseed the column. In other words, you can                            Secure your sensitive data with Grid-Tools'
     change the column’s seed value at any time. For instance, you might reseed a column after                              Enterprise Data Masking
                                                                                                                            www.grid-tools.com
     deleting records or moving data to an archive table.
                                                                                                                            Multilingual WebCenter
     The good news is that seeding and reseeding an identity column is easy and relatively safe, if you                     Translate Content Inside WebCenter Lingotek
     do it correctly. It’s common to seed a new table or to reseed a production, but empty table.                           Collaborative Translation
     However, as a general rule, it’s not a great idea to reseed an identity column in a table that                         lingotek.com/oracle
     contains data without some serious checks and balances.                                                                SQL Server Training
                                                                                                                            Access Videos, Articles and More. Join the
     Throughout this article, I use SQL Server Express and Management Studio Express because both                           SSWUG.ORG Community Today!
     are free and therefore available to all readers. However, the logic and instructions are the same in                   www.sswug.org
     SQL Server.

     This blog post is also available in the PDF format as a TechRepublic Download.
                                                                                                                       Keep Up with TechRepublic
     About identity
     Developers and writers alike tend to refer to SQL Server’s identity column property as a data type.
     It’s actually a column property. In purpose, it’s similar to Microsoft Access‘ AutoNumber column,
     although SQL Server’s identity column is more flexible. However, there are a few restrictions:                     
                                                                                                                             Five Apps
                                                                                                                        
                                                                                                                             Google in the Enterprise
        An identity column must be one of the following numeric data types: decimal, int, numeric,
        smallint, bigint, or tinyint.
                                                                                                                            Subscribe Today
        An identity column can’t accept or store NULL.
        Each table can contain only one identity column.
                                                                                                                       Follow us however you choose!
     When you create an identity column, you specify two values: Identity Seed and Identity Increment.
     The seed value specifies the column’s first (or next) value. SQL Server adds the increment value



http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
How do I... Reseed a SQL Server identity column? | TechRepublic




     to the last identity value to generate the next value, in sequence.

     For instance, a seed value of 1 and an increment value of 2 will generate the values 1, 3, 5, 7, and
     so on. By default, both the seed and incremental values are 1. Business rules often require a bit of
     customization.
                                                                                                                      Media Gallery
     Seeding
     Using Management Studio is probably the easiest way to seed an identity column when you create
     the table. In this case, it’s a simple matter of setting the appropriate property value, as you can
     see in Figure A. You can also use Management Studio to reseed an existing identity column.

     Figure A                                                                                                               PHOTO GALLERY (1 of 15)
                                                                                                                            Curiosity's autonomous
                                                                                                                            'seven minutes of...

                                                                                                                                  More Galleries »




                                                                                                                            VIDEO (1 of 13)
                                                                                                                            Cracking Open: HTC Titan II

                                                                                                                                   More Videos »



                                                                                                                      Hot Questions                     View All


                                                                                                                       3     SSL redirection



                                                                                                                       3     Switching from a Job to a career in
                                                                                                                             the IT field: Need an IT pro's
                                                                                                                             advice

     Seed an identity column when you create it in Management Studio.
                                                                                                                       2     windows 7 won't shutdown and
     If you create the table using code, you can easily seed the table’s identity column using the                           keeps switching on
     Transact-SQL (T-SQL) CREATE TABLE statement in the following form:

                                                                                                                       2     can anyone suggest if any such
     CREATE TABLE tablename
                                                                                                                             software exist with similar
     (                                                                                                                       functionality?

         columnname datatype identity [(seed, increment)
                                                                                                                      Ask a Question
         [NOT FOR REPLICATION]],

         [columnname ...]

     )                                                                                                                Hot Discussions                   View All

     In the code, datatype is a numeric column. Both seed and increment are optional and the default
                                                                                                                      221    Should developers be sued for
     value for both is 1.
                                                                                                                             security holes?
     Figure B shows the result of using CREATE TABLE to create a table named Orders and setting
     the OrderID column’s identity seed and increment values to 100 and 10, respectively. As you can                   79    The sitting duck that is open
     see, the first identity value is 100 and each subsequent value increases by 10. (You can decrease                       source
     identity values by specify a negative value for increment.)
                                                                                                                       27    Five fast Windows desktop search
     Figure B                                                                                                                utilities


                                                                                                                       30    Is the death knell sounding for
                                                                                                                             traditional antivirus?



http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
How do I... Reseed a SQL Server identity column? | TechRepublic




                                                                                                                      Start a Discussion



                                                                                                                      Blog Archive

                                                                                                                        August 2012        December 2011
                                                                                                                        July 2012          November 2011
                                                                                                                        June 2012          October 2011
                                                                                                                        May 2012           September 2011
                                                                                                                        April 2012         August 2011
                                                                                                                        March 2012         July 2011
                                                                                                                        February 2012      June 2011
                                                                                                                        January 2012




     Use CREATE TABLE to seed an identity column.

     Checking and reseeding
     For instance, if you copy all the table’s records to an archive table and then delete all the records
     in the source table, you might want to reseed the source table’s identity column, so you can
     control the sequence. Use T-SQL’s DBCC CHECKIDENT as follows to reseed an identity column:

     DBCC CHECKIDENT

     (

         tablename

         [, [NORESEED | RESEED [, newreseedvalue]]]

     )

     [WITH NO_INFOMSGS]

     Table A defines this statement’s optional parameters.

     Table A: DBCC CHECKIDENT
            Parameter                                             Description


                                  Returns the current identity value and the current maximum value of
      NORESEED
                                  the identity column, without reseeding. These values are usually (and
                                  should be) the same.

                                  Changes the current identity value, using the maximum value in the
      RESEED
                                  identity column, if the current identity value is less than the maximum
                                  identity value stored in the identity column.

                                  Specifies the new seed value when reseeding. If the table is empty,
                                  the first identity value (after executing DBCC CHECKIDENT) will equal
      newreseedvalue              newreseedvalue. If the table contains data, the next identity value will
                                  equal newreseedvalue + the current increment value (the default is 1).
                                  This behavior is new to SQL Server 2005 (and remains in 2008). SQL
                                  Server 2000 always increments the seed value.
      WITH NO INFOMSGS
                                  Suppresses all informational messages.




http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
How do I... Reseed a SQL Server identity column? | TechRepublic

     Technically, DBCC CHECKIDENT checks and corrects an identity value. Simply put, use it to learn
     the current identity value or to reseed an existing identity column.

     Checks
     Once a table’s in production, you might want to determine the seed value, as shown in Figure C.
     Executing DBCC CHECKIDENT with no argument other than the table’s name returns the
     column’s current identity value, which is the last value generated and stored in the table (see
     Figure B).

     Figure C




     Return an identity column’s current and maximum values.

     These two values will usually be the same. If they’re not, reset the identity value to avoid errors or
     gaps in the sequence of values.

     Balances
     SQL Server won’t execute a statement that duplicates existing identity values if the identity column
     is part of a primary key. Figure D shows what can happen when an identity column isn’t part of a
     primary key. In this case, DBCC CHECKIDENT reseeds OrderID and accepts a new record.
     However, the identity column generates a duplicate value. It’s important to remember that an
     identity column does not guarantee uniqueness.

     Figure D




http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
How do I... Reseed a SQL Server identity column? | TechRepublic

     What can happen when an identity column isn’t part of a primary key.

     When the identity column is part of a primary key, SQL Server protects the validity of the existing
     data by returning a violation error, as shown in Figure E. Now, the question is, did SQL Server
     reset the seed value or not — it did. You can reseed the column to a value that has the potential
     to create a duplicate, but SQL Server won’t let you enter the record. That’s why you must be
     careful to check existing identity values before reseeding.

     Figure E




     A violation error.

     When reseeding identity values, keep the following behaviors in mind:

        Setting the newreseed value below existing values will eventually generate an error if the
        column is part of a primary key.
        Use the exact seed value when running DBCC CHECKIDENT against a new table that has
        never contained data. For instance, a newreseed value of 10 will generate an initial identity
        value 10.
        When resetting an empty table (after deleting records), the identity column will generate
        newreseed + 1. If the next identity value should be 1, use a newreseed value of 0.
        Deleting records from a table using DELETE doesn’t reset an identity column; using
        TRUNCATE TABLE does. TRUNCATE TABLE is usually faster than DELETE, but in this case,
        not necessarily the best choice for the job, unless you mean to reset the identity column.

     Reseeding basics
     Reseeding an identity column is a common task, but you must know the basics or you might get
     into trouble. Specifically, an identity column can generate duplicate values. Knowing when and
     why is the key to keeping an identity column in check.

     Susan Sales Harkins is an independent consultant and the author of several articles and books on
     database technologies. Her most recent book is “Mastering Microsoft SQL Server 2005 Express,”
     with Mike Gunderloy, published by Sybex. Other collaborations with Mike Gunderloy are
     “Automating Microsoft Access 2003 with VBA,” “Upgrader’s Guide to Microsoft Office System
     2003,” “ICDL Exam Cram 2,” and “Absolute Beginner’s Guide to Microsoft Access 2003″ all by
     Que. Currently, Susan volunteers as the Publications Director for Database Advisors at
     http://www.databaseadvisors.com. You can reach her at ssharkins@gmail.com.


     Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free
     newsletters.




                  Disabling Customer                              Measure Dell M1000e and
                  Experience Improvement                          M600 Power Consumption
                  Program tasks in Windows
                  Server 2008



http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
How do I... Reseed a SQL Server identity column? | TechRepublic




        10            Join the conversation!                                              Add Your Opinion
      Comments        Follow via:



      Staff Picks      Top Rated      Most Recent        My Contacts                             See All Comments




                       IDENTITY columns                                                                0
                       sqllion 20th Aug 2011                                                         Votes



            All features of SQL Server IDENTITY property of columns. And a handy procedure to
            monitor all Identity columns. http://www.sqllion.com/2011/08/identity-in-sql/


                 View in thread




                       Useful, Thanks                                                                  0
                       epsilonv 24th Aug 2010                                                        Votes



            I had to execute the procedure twice for each table, first it set the current column and
            next time it set the current identity. I did it through Visual Studio though so that might
            have something to do... Read Whole Comment +


                 View in thread




                       RE: How do I... Reseed a SQL Server identity column?                            0
                       sqllion Updated - 21st Aug 2011                                               Votes


            For more information on Identifying and listing all the IDENTITY columns present in a
            given database with filtering option available for specific tables, refer the below link:...
            Read Whole Comment +


                 View in thread




                                                  See all comments



     Join the TechRepublic Community and join the conversation! Signing-up is
     free and quick, Do it now, we want to hear your opinion.

       Join        Login




http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]

Contenu connexe

En vedette

Val-d'Oise / Tableau de bord emploi-formation
Val-d'Oise / Tableau de bord emploi-formationVal-d'Oise / Tableau de bord emploi-formation
Val-d'Oise / Tableau de bord emploi-formationDefi_metiers
 
FA Falls 2 Teresa O'Callaghan
FA Falls 2 Teresa O'CallaghanFA Falls 2 Teresa O'Callaghan
FA Falls 2 Teresa O'Callaghananne spencer
 
Qualité et FOAD - webconference FFFOD du 13/10/2015
Qualité et FOAD - webconference FFFOD du 13/10/2015Qualité et FOAD - webconference FFFOD du 13/10/2015
Qualité et FOAD - webconference FFFOD du 13/10/2015FFFOD
 
виборчий марафон
виборчий марафонвиборчий марафон
виборчий марафонufkbyf2205
 
день цивільного захисту
день цивільного захистудень цивільного захисту
день цивільного захистуufkbyf2205
 
Dossier De Stage Greta
Dossier De Stage                   GretaDossier De Stage                   Greta
Dossier De Stage Gretayouri59490
 

En vedette (7)

Val-d'Oise / Tableau de bord emploi-formation
Val-d'Oise / Tableau de bord emploi-formationVal-d'Oise / Tableau de bord emploi-formation
Val-d'Oise / Tableau de bord emploi-formation
 
Bala murali sapui5 abapcv
Bala murali sapui5 abapcvBala murali sapui5 abapcv
Bala murali sapui5 abapcv
 
FA Falls 2 Teresa O'Callaghan
FA Falls 2 Teresa O'CallaghanFA Falls 2 Teresa O'Callaghan
FA Falls 2 Teresa O'Callaghan
 
Qualité et FOAD - webconference FFFOD du 13/10/2015
Qualité et FOAD - webconference FFFOD du 13/10/2015Qualité et FOAD - webconference FFFOD du 13/10/2015
Qualité et FOAD - webconference FFFOD du 13/10/2015
 
виборчий марафон
виборчий марафонвиборчий марафон
виборчий марафон
 
день цивільного захисту
день цивільного захистудень цивільного захисту
день цивільного захисту
 
Dossier De Stage Greta
Dossier De Stage                   GretaDossier De Stage                   Greta
Dossier De Stage Greta
 

Similaire à How do i... reseed a sql server identity column tech_republic

Filtered indexes in sql server 2008 tech republic
Filtered indexes in sql server 2008   tech republicFiltered indexes in sql server 2008   tech republic
Filtered indexes in sql server 2008 tech republicKaing Menglieng
 
ServerTemplate Deep Dive
ServerTemplate Deep DiveServerTemplate Deep Dive
ServerTemplate Deep DiveRightScale
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Julien Simon "Scaling ML from 0 to millions of users"
Julien Simon "Scaling ML from 0 to millions of users"Julien Simon "Scaling ML from 0 to millions of users"
Julien Simon "Scaling ML from 0 to millions of users"Fwdays
 
Sql interview question part 4
Sql interview question part 4Sql interview question part 4
Sql interview question part 4kaashiv1
 
Sql interview question part 4
Sql interview question part 4Sql interview question part 4
Sql interview question part 4kaashiv1
 
Automated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE ApplicationsAutomated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE ApplicationsJelastic Multi-Cloud PaaS
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republicKaing Menglieng
 
Practical Cloud & Workflow Orchestration
Practical Cloud & Workflow OrchestrationPractical Cloud & Workflow Orchestration
Practical Cloud & Workflow OrchestrationChris Dagdigian
 
20141021 AWS Cloud Taekwon - Startup Best Practices on AWS
20141021 AWS Cloud Taekwon - Startup Best Practices on AWS20141021 AWS Cloud Taekwon - Startup Best Practices on AWS
20141021 AWS Cloud Taekwon - Startup Best Practices on AWSAmazon Web Services Korea
 
Geek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database MirroringGeek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database MirroringIDERA Software
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesSQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesEduardo Castro
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copyMustafa EL-Masry
 
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019Provectus
 
SQL Injection Attacks: Is Your Data Secure? .NET Edition
SQL Injection Attacks: Is Your Data Secure? .NET EditionSQL Injection Attacks: Is Your Data Secure? .NET Edition
SQL Injection Attacks: Is Your Data Secure? .NET EditionBert Wagner
 

Similaire à How do i... reseed a sql server identity column tech_republic (20)

Filtered indexes in sql server 2008 tech republic
Filtered indexes in sql server 2008   tech republicFiltered indexes in sql server 2008   tech republic
Filtered indexes in sql server 2008 tech republic
 
ServerTemplate Deep Dive
ServerTemplate Deep DiveServerTemplate Deep Dive
ServerTemplate Deep Dive
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Julien Simon "Scaling ML from 0 to millions of users"
Julien Simon "Scaling ML from 0 to millions of users"Julien Simon "Scaling ML from 0 to millions of users"
Julien Simon "Scaling ML from 0 to millions of users"
 
Sql interview question part 4
Sql interview question part 4Sql interview question part 4
Sql interview question part 4
 
Ebook4
Ebook4Ebook4
Ebook4
 
Sql interview question part 4
Sql interview question part 4Sql interview question part 4
Sql interview question part 4
 
Automated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE ApplicationsAutomated Scaling of Microservice Stacks for JavaEE Applications
Automated Scaling of Microservice Stacks for JavaEE Applications
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republic
 
Sql tuning
Sql tuningSql tuning
Sql tuning
 
Data In Cloud
Data In CloudData In Cloud
Data In Cloud
 
Practical Cloud & Workflow Orchestration
Practical Cloud & Workflow OrchestrationPractical Cloud & Workflow Orchestration
Practical Cloud & Workflow Orchestration
 
20141021 AWS Cloud Taekwon - Startup Best Practices on AWS
20141021 AWS Cloud Taekwon - Startup Best Practices on AWS20141021 AWS Cloud Taekwon - Startup Best Practices on AWS
20141021 AWS Cloud Taekwon - Startup Best Practices on AWS
 
Geek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database MirroringGeek Sync | Field Medic’s Guide to Database Mirroring
Geek Sync | Field Medic’s Guide to Database Mirroring
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesSQL Server 2008 Integration Services
SQL Server 2008 Integration Services
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copy
 
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
"Scaling ML from 0 to millions of users", Julien Simon, AWS Dev Day Kyiv 2019
 
Running a Lean Startup with AWS
Running a Lean Startup with AWSRunning a Lean Startup with AWS
Running a Lean Startup with AWS
 
SQL Injection Attacks: Is Your Data Secure? .NET Edition
SQL Injection Attacks: Is Your Data Secure? .NET EditionSQL Injection Attacks: Is Your Data Secure? .NET Edition
SQL Injection Attacks: Is Your Data Secure? .NET Edition
 

Plus de Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republicKaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projecKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republicKaing Menglieng
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republicKaing Menglieng
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republicKaing Menglieng
 
How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services Kaing Menglieng
 

Plus de Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republic
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projec
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republic
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republic
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republic
 
How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services
 

How do i... reseed a sql server identity column tech_republic

  • 1. How do I... Reseed a SQL Server identity column? | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud How do I... Reseed a SQL Server identity column? By Susan Harkins July 15, 2008, 11:53 AM PDT Microsoft SQL Server’s identity column generates sequential values for new records using a seed value. The term seed refers to the internal value SQL Server uses to generate the next value in the sequence. By default, an identity column’s first value is 1 and each new value increments by one (1, 2, 3, 4, and so on). You can control the column’s first and subsequent values, by specifying those values when you create the column. For instance, you might want to begin with a purchase order number of 1001 Data Masking rather than 1. Software Once the table’s in production you can reset, or reseed the column. In other words, you can Secure your sensitive data with Grid-Tools' change the column’s seed value at any time. For instance, you might reseed a column after Enterprise Data Masking www.grid-tools.com deleting records or moving data to an archive table. Multilingual WebCenter The good news is that seeding and reseeding an identity column is easy and relatively safe, if you Translate Content Inside WebCenter Lingotek do it correctly. It’s common to seed a new table or to reseed a production, but empty table. Collaborative Translation However, as a general rule, it’s not a great idea to reseed an identity column in a table that lingotek.com/oracle contains data without some serious checks and balances. SQL Server Training Access Videos, Articles and More. Join the Throughout this article, I use SQL Server Express and Management Studio Express because both SSWUG.ORG Community Today! are free and therefore available to all readers. However, the logic and instructions are the same in www.sswug.org SQL Server. This blog post is also available in the PDF format as a TechRepublic Download. Keep Up with TechRepublic About identity Developers and writers alike tend to refer to SQL Server’s identity column property as a data type. It’s actually a column property. In purpose, it’s similar to Microsoft Access‘ AutoNumber column, although SQL Server’s identity column is more flexible. However, there are a few restrictions: Five Apps Google in the Enterprise An identity column must be one of the following numeric data types: decimal, int, numeric, smallint, bigint, or tinyint. Subscribe Today An identity column can’t accept or store NULL. Each table can contain only one identity column. Follow us however you choose! When you create an identity column, you specify two values: Identity Seed and Identity Increment. The seed value specifies the column’s first (or next) value. SQL Server adds the increment value http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
  • 2. How do I... Reseed a SQL Server identity column? | TechRepublic to the last identity value to generate the next value, in sequence. For instance, a seed value of 1 and an increment value of 2 will generate the values 1, 3, 5, 7, and so on. By default, both the seed and incremental values are 1. Business rules often require a bit of customization. Media Gallery Seeding Using Management Studio is probably the easiest way to seed an identity column when you create the table. In this case, it’s a simple matter of setting the appropriate property value, as you can see in Figure A. You can also use Management Studio to reseed an existing identity column. Figure A PHOTO GALLERY (1 of 15) Curiosity's autonomous 'seven minutes of... More Galleries » VIDEO (1 of 13) Cracking Open: HTC Titan II More Videos » Hot Questions View All 3 SSL redirection 3 Switching from a Job to a career in the IT field: Need an IT pro's advice Seed an identity column when you create it in Management Studio. 2 windows 7 won't shutdown and If you create the table using code, you can easily seed the table’s identity column using the keeps switching on Transact-SQL (T-SQL) CREATE TABLE statement in the following form: 2 can anyone suggest if any such CREATE TABLE tablename software exist with similar ( functionality? columnname datatype identity [(seed, increment) Ask a Question [NOT FOR REPLICATION]], [columnname ...] ) Hot Discussions View All In the code, datatype is a numeric column. Both seed and increment are optional and the default 221 Should developers be sued for value for both is 1. security holes? Figure B shows the result of using CREATE TABLE to create a table named Orders and setting the OrderID column’s identity seed and increment values to 100 and 10, respectively. As you can 79 The sitting duck that is open see, the first identity value is 100 and each subsequent value increases by 10. (You can decrease source identity values by specify a negative value for increment.) 27 Five fast Windows desktop search Figure B utilities 30 Is the death knell sounding for traditional antivirus? http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
  • 3. How do I... Reseed a SQL Server identity column? | TechRepublic Start a Discussion Blog Archive August 2012 December 2011 July 2012 November 2011 June 2012 October 2011 May 2012 September 2011 April 2012 August 2011 March 2012 July 2011 February 2012 June 2011 January 2012 Use CREATE TABLE to seed an identity column. Checking and reseeding For instance, if you copy all the table’s records to an archive table and then delete all the records in the source table, you might want to reseed the source table’s identity column, so you can control the sequence. Use T-SQL’s DBCC CHECKIDENT as follows to reseed an identity column: DBCC CHECKIDENT ( tablename [, [NORESEED | RESEED [, newreseedvalue]]] ) [WITH NO_INFOMSGS] Table A defines this statement’s optional parameters. Table A: DBCC CHECKIDENT Parameter Description Returns the current identity value and the current maximum value of NORESEED the identity column, without reseeding. These values are usually (and should be) the same. Changes the current identity value, using the maximum value in the RESEED identity column, if the current identity value is less than the maximum identity value stored in the identity column. Specifies the new seed value when reseeding. If the table is empty, the first identity value (after executing DBCC CHECKIDENT) will equal newreseedvalue newreseedvalue. If the table contains data, the next identity value will equal newreseedvalue + the current increment value (the default is 1). This behavior is new to SQL Server 2005 (and remains in 2008). SQL Server 2000 always increments the seed value. WITH NO INFOMSGS Suppresses all informational messages. http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
  • 4. How do I... Reseed a SQL Server identity column? | TechRepublic Technically, DBCC CHECKIDENT checks and corrects an identity value. Simply put, use it to learn the current identity value or to reseed an existing identity column. Checks Once a table’s in production, you might want to determine the seed value, as shown in Figure C. Executing DBCC CHECKIDENT with no argument other than the table’s name returns the column’s current identity value, which is the last value generated and stored in the table (see Figure B). Figure C Return an identity column’s current and maximum values. These two values will usually be the same. If they’re not, reset the identity value to avoid errors or gaps in the sequence of values. Balances SQL Server won’t execute a statement that duplicates existing identity values if the identity column is part of a primary key. Figure D shows what can happen when an identity column isn’t part of a primary key. In this case, DBCC CHECKIDENT reseeds OrderID and accepts a new record. However, the identity column generates a duplicate value. It’s important to remember that an identity column does not guarantee uniqueness. Figure D http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
  • 5. How do I... Reseed a SQL Server identity column? | TechRepublic What can happen when an identity column isn’t part of a primary key. When the identity column is part of a primary key, SQL Server protects the validity of the existing data by returning a violation error, as shown in Figure E. Now, the question is, did SQL Server reset the seed value or not — it did. You can reseed the column to a value that has the potential to create a duplicate, but SQL Server won’t let you enter the record. That’s why you must be careful to check existing identity values before reseeding. Figure E A violation error. When reseeding identity values, keep the following behaviors in mind: Setting the newreseed value below existing values will eventually generate an error if the column is part of a primary key. Use the exact seed value when running DBCC CHECKIDENT against a new table that has never contained data. For instance, a newreseed value of 10 will generate an initial identity value 10. When resetting an empty table (after deleting records), the identity column will generate newreseed + 1. If the next identity value should be 1, use a newreseed value of 0. Deleting records from a table using DELETE doesn’t reset an identity column; using TRUNCATE TABLE does. TRUNCATE TABLE is usually faster than DELETE, but in this case, not necessarily the best choice for the job, unless you mean to reset the identity column. Reseeding basics Reseeding an identity column is a common task, but you must know the basics or you might get into trouble. Specifically, an identity column can generate duplicate values. Knowing when and why is the key to keeping an identity column in check. Susan Sales Harkins is an independent consultant and the author of several articles and books on database technologies. Her most recent book is “Mastering Microsoft SQL Server 2005 Express,” with Mike Gunderloy, published by Sybex. Other collaborations with Mike Gunderloy are “Automating Microsoft Access 2003 with VBA,” “Upgrader’s Guide to Microsoft Office System 2003,” “ICDL Exam Cram 2,” and “Absolute Beginner’s Guide to Microsoft Access 2003″ all by Que. Currently, Susan volunteers as the Publications Director for Database Advisors at http://www.databaseadvisors.com. You can reach her at ssharkins@gmail.com. Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free newsletters. Disabling Customer Measure Dell M1000e and Experience Improvement M600 Power Consumption Program tasks in Windows Server 2008 http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]
  • 6. How do I... Reseed a SQL Server identity column? | TechRepublic 10 Join the conversation! Add Your Opinion Comments Follow via: Staff Picks Top Rated Most Recent My Contacts See All Comments IDENTITY columns 0 sqllion 20th Aug 2011 Votes All features of SQL Server IDENTITY property of columns. And a handy procedure to monitor all Identity columns. http://www.sqllion.com/2011/08/identity-in-sql/ View in thread Useful, Thanks 0 epsilonv 24th Aug 2010 Votes I had to execute the procedure twice for each table, first it set the current column and next time it set the current identity. I did it through Visual Studio though so that might have something to do... Read Whole Comment + View in thread RE: How do I... Reseed a SQL Server identity column? 0 sqllion Updated - 21st Aug 2011 Votes For more information on Identifying and listing all the IDENTITY columns present in a given database with filtering option available for specific tables, refer the below link:... Read Whole Comment + View in thread See all comments Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/how-do-i-reseed-a-sql-server-identity-column/406[08/29/2012 3:38:07 PM]