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

后端 未结 13 1968
借酒劲吻你
借酒劲吻你 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:07

    I think this works for SQL 2000:

    SELECT 
        CASE WHEN C.autoval IS NOT NULL THEN
            'Identity'
        ELSE
            'Not Identity'
        AND
    FROM
        sysobjects O
    INNER JOIN
        syscolumns C
    ON
        O.id = C.id
    WHERE
        O.NAME = @TableName
    AND
        C.NAME = @ColumnName
    
    0 讨论(0)
  • 2020-12-01 00:08

    This query seems to do the trick:

    SELECT 
        sys.objects.name AS table_name, 
        sys.columns.name AS column_name
    FROM sys.columns JOIN sys.objects 
        ON sys.columns.object_id=sys.objects.object_id
    WHERE 
        sys.columns.is_identity=1
        AND
        sys.objects.type in (N'U')
    
    0 讨论(0)
  • 2020-12-01 00:08

    By some reason sql server save some identity columns in different tables, the code that work for me, is the following:

    select      TABLE_NAME tabla,COLUMN_NAME columna
    from        INFORMATION_SCHEMA.COLUMNS
    where       COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
    union all
    select      o.name tabla, c.name columna
    from        sys.objects o 
    inner join  sys.columns c on o.object_id = c.object_id
    where       c.is_identity = 1
    
    0 讨论(0)
  • 2020-12-01 00:09

    sys.columns.is_identity = 1

    e.g.,

    select o.name, c.name
    from sys.objects o inner join sys.columns c on o.object_id = c.object_id
    where c.is_identity = 1
    
    0 讨论(0)
  • 2020-12-01 00:14

    The following query work for me:

    select  TABLE_NAME tabla,COLUMN_NAME columna
    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:18

    Use this :

    DECLARE @Table_Name VARCHAR(100) 
    DECLARE @Column_Name VARCHAR(100)
    SET @Table_Name = ''
    SET @Column_Name = ''
    
    SELECT  RowNumber = ROW_NUMBER() OVER ( PARTITION BY T.[Name] ORDER BY T.[Name], C.column_id ) ,
        SCHEMA_NAME(T.schema_id) AS SchemaName ,
        T.[Name] AS Table_Name ,
        C.[Name] AS Field_Name ,
        sysType.name ,
        C.max_length ,
        C.is_nullable ,
        C.is_identity ,
        C.scale ,
        C.precision
    FROM    Sys.Tables AS T
        LEFT JOIN Sys.Columns AS C ON ( T.[Object_Id] = C.[Object_Id] )
        LEFT JOIN sys.types AS sysType ON ( C.user_type_id = sysType.user_type_id )
    WHERE   ( Type = 'U' )
        AND ( C.Name LIKE '%' + @Column_Name + '%' )
        AND ( T.Name LIKE '%' + @Table_Name + '%' )
    ORDER BY T.[Name] ,
        C.column_id
    
    0 讨论(0)
提交回复
热议问题