How do you determine what SQL Tables have an identity column programmatically

后端 未结 13 1970
借酒劲吻你
借酒劲吻你 2020-11-30 23:44

I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.

Results would be something like:

Tab

相关标签:
13条回答
  • 2020-12-01 00:22

    here's a working version for MSSQL 2000. I've modified the 2005 code found here: http://sqlfool.com/2011/01/identity-columns-are-you-nearing-the-limits/

    /* Define how close we are to the value limit
       before we start throwing up the red flag.
       The higher the value, the closer to the limit. */
    DECLARE @threshold DECIMAL(3,2);
    SET @threshold = .85;
    
    /* Create a temp table */
    CREATE TABLE #identityStatus
    (
          database_name     VARCHAR(128)
        , table_name        VARCHAR(128)
        , column_name       VARCHAR(128)
        , data_type         VARCHAR(128)
        , last_value        BIGINT
        , max_value         BIGINT
    );
    
    DECLARE @dbname sysname;
    DECLARE @sql nvarchar(4000);
    
    -- Use an cursor to iterate through the databases since in 2000 there's no sp_MSForEachDB command...
    
    DECLARE c cursor FAST_FORWARD FOR
    SELECT
        name
    FROM
        master.dbo.sysdatabases 
    WHERE 
        name NOT IN('master', 'model', 'msdb', 'tempdb');
    
    OPEN c;
    
    FETCH NEXT FROM c INTO @dbname;
    
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @sql = N'Use [' + @dbname + '];
        Insert Into #identityStatus
        Select ''' + @dbname + ''' As [database_name]
            , Object_Name(id.id) As [table_name]
            , id.name As [column_name]
            , t.name As [data_type]
            , IDENT_CURRENT(Object_Name(id.id)) As [last_value]
            , Case 
                When t.name = ''tinyint''   Then 255 
                When t.name = ''smallint''  Then 32767 
                When t.name = ''int''       Then 2147483647 
                When t.name = ''bigint''    Then 9223372036854775807
              End As [max_value]
        From 
            syscolumns As id
            Join systypes As t On id.xtype = t.xtype
        Where 
            id.colstat&1 = 1    -- this identifies the identity columns (as far as I know)
        ';
    
        EXECUTE sp_executesql @sql;
    
        FETCH NEXT FROM c INTO @dbname;
    END
    
    CLOSE c;
    DEALLOCATE c;
    
    /* Retrieve our results and format it all prettily */
    SELECT database_name
        , table_name
        , column_name
        , data_type
        , last_value
        , CASE 
            WHEN last_value < 0 THEN 100
            ELSE (1 - CAST(last_value AS FLOAT(4)) / max_value) * 100 
          END AS [percentLeft]
        , CASE 
            WHEN CAST(last_value AS FLOAT(4)) / max_value >= @threshold
                THEN 'warning: approaching max limit'
            ELSE 'okay'
            END AS [id_status]
    FROM #identityStatus
    ORDER BY percentLeft;
    
    /* Clean up after ourselves */
    DROP TABLE #identityStatus;
    
    0 讨论(0)
  • 2020-12-01 00:25

    Another way (for 2000 / 2005/2012/2014):

    IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)
        PRINT 'Yes'
    ELSE
        PRINT 'No'
    

    NOTE: table_name_here should be schema.table, unless the schema is dbo.

    0 讨论(0)
  • 2020-12-01 00:25

    In SQL 2005:

    select object_name(object_id), name
    from sys.columns
    where is_identity = 1
    
    0 讨论(0)
  • 2020-12-01 00:25

    This worked for SQL Server 2005, 2008, and 2012. I found that the sys.identity_columns did not contain all my tables with identity columns.

    SELECT a.name AS TableName, b.name AS IdentityColumn
    FROM sys.sysobjects a 
    JOIN sys.syscolumns b 
    ON a.id = b.id
    WHERE is_identity = 1
    ORDER BY name;
    

    Looking at the documentation page the status column can also be utilized. Also you can add the four part identifier and it will work across different servers.

    SELECT a.name AS TableName, b.name AS IdentityColumn
    FROM [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.sysobjects a 
    JOIN [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.syscolumns b 
    ON a.id = b.id
    WHERE is_identity = 1
    ORDER BY name;
    

    Source: https://msdn.microsoft.com/en-us/library/ms186816.aspx

    0 讨论(0)
  • 2020-12-01 00:26

    Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION_SCHEMA views:

    select COLUMN_NAME, TABLE_NAME
    from INFORMATION_SCHEMA.COLUMNS
    where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    order by TABLE_NAME 
    
    0 讨论(0)
  • 2020-12-01 00:29

    This worked for me using Sql Server 2008:

    USE <database_name>;
    GO
    SELECT SCHEMA_NAME(schema_id) AS schema_name
        , t.name AS table_name
        , c.name AS column_name
    FROM sys.tables AS t
    JOIN sys.identity_columns c ON t.object_id = c.object_id
    ORDER BY schema_name, table_name;
    GO
    
    0 讨论(0)
提交回复
热议问题