Finding Identity Columns–#SQLNewBlogger

·

I had to find a set of identity columns recently and through this would make a good blog post.

Another post for me that is simple and hopefully serves as an example for people trying to get blogging as #SQLNewBloggers.

Getting a List of Tables and Columns with Identity Properties

Finding out which tables have an identity isn’t very easy, especially in SSMS’s Object Explorer. This property is somewhat hidden, which is annoying to me as I use them often. However, I get this is just a property.

This is, however, stored in sys.columns.is_identity. This is set to 1 if the property is set, so filtering on this is good thing. If we join to sys.columns on object_id, we can get a list of table names.

Here’s a short script to do this.

SELECT
   o.name AS TableName
, columns.name AS ColumnName
, is_identity
FROM
   sys.columns
   INNER JOIN sys.objects AS o
     ON o.object_id = columns.object_id
WHERE sys.columns.is_identity = 1;

However, there’s an easier way. There is a sys.identity_columns view which inherits from sys.columns and does the filtering for you. You can use this code instead.

SELECT
  o.name AS TableName
, columns.name AS ColumnName
, is_identity
FROM
  sys.identity_columns AS columns
  INNER JOIN sys.objects AS o
    ON o.object_id = columns.object_id

SQL New Blogger

I had to do this as a quick test for a client that wanted to do some checking of identity seeds. They asked for a list of tables to check, and I showed them how to get this quickly.

This was literally about 2 minutes to set up and about 5 minutes to write this post. Something you could easily do.

Comments

5 responses to “Finding Identity Columns–#SQLNewBlogger”

  1. JeffModen Avatar
    JeffModen

    To be honest, if a customer didn’t know how to do this but wanted to know because they were going to check identity seeds, I’d be very concerned about their work in the latter task.

    Good post, though, Steve.

    Like

    1. way0utwest Avatar

      Not sure I’d agree with that. Plenty of devs inherit systems and don’t know what’s set up. They might want to get a list of tables and check if there are any tables nearing the end of their values.

      Thanks for the complement.

      Like

    2. JeffModen Avatar
      JeffModen

      Heh… I guess we’ll have to agree to disagree.

      Like

    3. way0utwest Avatar

      As we often do 😉

      Like

    4. JeffModen Avatar
      JeffModen

      As a bit of a sidebar, that’s one of the reasons why I like working with you, Steve. Seriously, thanks for being there and thank you for what you do!

      Like