How to identify whether the table has identity column

大兔子大兔子 提交于 2019-12-04 23:43:52
Pranay Rana

This is the query which return identity column name;

create procedure GetIdentity 
@tablename varchar(50)
begin
    SELECT   OBJECT_NAME(OBJECT_ID) AS TABLENAME, 
             NAME AS COLUMNNAME, 
             SEED_VALUE, 
             INCREMENT_VALUE, 
             LAST_VALUE, 
             IS_NOT_FOR_REPLICATION 
    FROM     SYS.IDENTITY_COLUMNS 
    WHERE OBJECT_NAME(OBJECT_ID) = @tablename
end

Then form the code side.

Call this stored procedure using the datareader role, then check datareader.hasrows(). If the condition value is true (1), then the table has identity column if set. If not then it doesn't have an identity column.

I know it's long time ago but i found this helpful

try this :

IF EXISTS (SELECT * from syscolumns where id = Object_ID(@TABLE_NAME) and colstat & 1 = 1)
BEGIN
   -- Do your things
END
h3n
IF (OBJECTPROPERTY(OBJECT_ID('TABLE_NAME'), 'TableHasIdentity') = 1) 

ObjectProperty is available starting sql server 2008 Reference: OBJECTPROPERTY

Bhavneet

Any of the below queries can be used to check if an Identity Column is present in the table

1)

SELECT *
FROM sys.identity_columns
WHERE OBJECT_NAME(object_id) = 'TableName'

2)

SELECT *
FROM sys.identity_columns
WHERE object_id = (
        SELECT id
        FROM sysobjects
        WHERE name = 'TableName'
    )

I would just like to add this option as well as I think it is the simplest

SELECT COLUMNPROPERTY(OBJECT_ID('TableName'),'ColumnName','isidentity')

One way to do this would be to make use of the stored procedure sp_help. I.e:

sp_help MyTable

This will return a DataSet that has all the information you would need on the table. There is a specific Table that has information on identities.

I.e:

If it does not contain an identity field, the Identity column will say: "No identity column defined".

@Pranay: he said Compact Edition. Stored procedures aren't supported, and there is no sys.anything.

This is the call:

SELECT Count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE AUTOINC_INCREMENT IS NOT NULL AND TABLE_NAME='this_table'

It will return either 1 (true) or 0 (false).

Aravind Goud

This the query that get u all the tableNames, columnnames of the table, and is_identity or not in the selected database

SELECT
     sys.columns.name
   , sys.tables.name
   , is_identity
FROM sys.columns
INNER JOIN sys.tables ON sys.tables.object_id = sys.columns.object_id
    AND sys.columns.is_identity = 1

you can get the 1 or 0 Boolean Form if the current table has identity Columns by using this

SELECT Count(Column_ID) FROM sys.identity_columns WHERE OBJECT_NAME(object_id) = 'tableName'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!