SQL Server : collation set to insensitive is ignored - sql

I have database with table 'Product', column 'Name'. I need to implement case and accent insensitive search so I tried to change collation of the column like this:
EXEC sp_fulltext_column #tabname = 'Product' , #colname = 'Name', #action = 'drop'
ALTER TABLE dbo.Product
ALTER COLUMN Name nvarchar(400) COLLATE SQL_Latin1_General_CP1_CI_AI NOT NULL;
EXEC sp_fulltext_column #tabname = 'Product' , #colname = 'Name', #action = 'add'
Then I checked the collation of the column like this:
SELECT collation_name FROM sys.columns
WHERE name = 'name' AND object_id = (select object_id from sys.tables where name = 'Product');
And collation is set correctly to CI and AI (SQL_Latin1_General_CP1_CI_AI).
I have test products in database with names like 'Čučoriedka', 'Čúčo', 'Test'.
I would like to be able select 'Čučoriedka' and 'Čúčo' by query:
select * from product where CONTAINS([Name], 'cuc')
But neither 'test' is working with this queries:
select * from product where CONTAINS([Name], 'tes')
select * from product where PATINDEX('tes', [Name] COLLATE SQL_Latin1_General_CP1_CI_AI ) > 0
I tried also another collations, but nothing works.
Do you have any idea what can help here?
Thanks a lot! Marek

I found the solution! I found out that, collation has impact only for ordering. I'm using fulltext search so I need to change fulltext indexes. Here is how I did if anyone else need do the same..
IF EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id('Product'))
DROP FULLTEXT INDEX ON [Product]
DECLARE #create_index_text nvarchar(4000)
SET #create_index_text = '
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(''[Product]''))
ALTER FULLTEXT INDEX ON [Product]([Name] Language 1051, [ShortDescription] Language 1051, [FullDescription] Language 1051, [Sku] Language 1051)
KEY INDEX [' + dbo.[nop_getprimarykey_indexname] ('Product') + '] ON [nopCommerceFullTextCatalog] WITH CHANGE_TRACKING AUTO'
EXEC(#create_index_text)
ALTER FULLTEXT CATALOG nopCommerceFullTextCatalog REBUILD WITH ACCENT_SENSITIVITY=OFF;
The language code 1051 is for slovak language, you can find your code here: http://technet.microsoft.com/en-us/library/ms176076.aspx
Hope it helps!

Related

How can I check if the table behind a synonym exists

I'm trying to create a simple script to dump the results of a complex view out into a table for reporting. I have used synonyms to simplify tweaking the view and table names.
The idea is that the user of the script can put the name of the view they want to use as the source, and the name of the target reporting table in at the start and away they go. If the table doesn't exist then the script should create it. If the table already exists then the script should only copy the records from the view which aren't already in the table over.
The script below covers all those requirements, but I can't find a nice way to check if the table behind the synonym already exists:
CREATE SYNONYM SourceView FOR my_view
CREATE SYNONYM TargetReportingTable FOR my_table
-- Here's where I'm having trouble, how do I check if the underlying table exists?
IF (SELECT COUNT(*) FROM information_schema.tables WHERE table_name = TargetReportingTable) = 0
BEGIN
-- Table does not exists, so insert into.
SELECT * INTO TargetReportingTable FROM SourceView
END
ELSE
BEGIN
-- Table already exists so work out the last record which was copied over
-- and insert only the newer records.
DECLARE #LastReportedRecordId INT;
SET #LastReportedRecordId = (SELECT MAX(RecordId) FROM TargetReportingTable)
INSERT INTO TargetReportingTable SELECT * FROM SourceView WHERE RecordId > #LastReportedRecordId
END
DROP SYNONYM SourceView
DROP SYNONYM TargetReportingTable
I know I could just get the user of the script to copy the table name into the 'information_schema' line as well as into the synonym at the top, but that leaves scope for error.
I also know I could do something filthy like put the table name into a variable and blat the SQL out as a string, but that makes me feel a bit sick!
Is there a nice elegant SQL way for me to check if the table behind the synonym exists? Or a totally different way to solve to problem?
Not the most elegant of solutions, but you could join the sys.synonyms table to the sys.tables table to check whether the table exists.
If the table does not exist, the join will fail and you will get 0 rows (hence IF EXISTS will be false). If the table does exist, the join will success and you will get 1 row (and true):
IF EXISTS( SELECT *
FROM sys.synonyms s
INNER JOIN sys.tables t ON REPLACE(REPLACE(s.base_object_name, '[', ''), ']', '') = t.name
WHERE s.name = 'TargetReportingTable')
BEGIN
-- Does exist
END
ELSE
BEGIN
-- Does not exist
END
Replace 'TargetReportingTable' with whichever synonym you wish to check.
The above solutions did not work for me if the synonym referenced another database. I recently discovered the function [fn_my_permissions] which is useful for showing permissions for a specific database object, so I figure this could be used as follows:
IF EXISTS
(
select *
from sys.synonyms sy
cross apply fn_my_permissions(sy.base_object_name, 'OBJECT')
WHERE sy.name = 'TargetReportingTable'
)
print 'yes - I exist!'
Late to the party, I have created a query to test out the existence of Synonyms and share with you.
DECLARE #Synonyms table
(
ID int identity(1,1),
SynonymsDatabaseName sysname,
SynonymsSchemaName sysname,
SynonymsName sysname,
DatabaseName nvarchar(128),
SchemaName nvarchar(128),
ObjectName nvarchar(128),
Remark nvarchar(max),
IsExists bit default(0)
)
INSERT #Synonyms (SynonymsDatabaseName, SynonymsSchemaName, SynonymsName, DatabaseName, SchemaName, ObjectName)
SELECT
DB_NAME() AS SynonymsDatabaseName,
SCHEMA_NAME(schema_id) AS SynonymsSchemaName,
name AS SynonymsName,
PARSENAME(base_object_name,3) AS DatabaseName,
PARSENAME(base_object_name,2) AS SchemaName,
PARSENAME(base_object_name,1) AS ObjectName
FROM sys.synonyms
SET NOCOUNT ON
DECLARE #ID int = 1, #Query nvarchar(max), #Remark nvarchar(max)
WHILE EXISTS(SELECT * FROM #Synonyms WHERE ID = #ID)
BEGIN
SELECT
#Query = 'SELECT #Remark = o.type_desc FROM [' + DatabaseName + '].sys.objects o INNER JOIN sys.schemas s ON o.schema_id = s.schema_id WHERE s.name = ''' + SchemaName + ''' AND o.name = ''' + ObjectName + ''''
FROM #Synonyms WHERE ID = #ID
EXEC sp_executesql #Query, N'#Remark nvarchar(max) OUTPUT', #Remark OUTPUT;
UPDATE #Synonyms SET IsExists = CASE WHEN #Remark IS NULL THEN 0 ELSE 1 END, Remark = #Remark WHERE ID = #ID
SELECT #ID += 1, #Remark = NULL
END
SELECT * FROM #Synonyms
You can do this with dynamic SQL:
-- create synonym a for information_schema.tables
create synonym a for b
declare #exists int = 1;
begin try
exec('select top 0 * from a');
end try
begin catch
set #exists = 0;
end catch
select #exists;
This doesn't work with non-dynamic SQL, because the synonym reference is caught at compile-time. That means that the code just fails with a message and is not caught by the try/catch block. With dynamic SQL, the block catches the error.
You can test if Synonym exists in your database using the Object_Id function avaliable in SQL Server
IF OBJECT_ID('YourDatabaseName..YourSynonymName') IS NOT NULL
PRINT 'Exist SYNONYM'
ELSE
PRINT 'Not Exist SYNONYM'
Another simpler solution:
IF (EXISTS (SELECT * FROM sys.synonyms WHERE NAME ='mySynonymName'))
BEGIN
UPDATE mySynonymName
SET [Win] = 1
END
In this case, I do database setup first. I drop all Synonyms in my database (database1) first, then run a SPROC to create synonyms for all tables in the destination database(database2).
Some SPROCS in database1 call on tables in DB2. If table doesnt exist in DB2 the SPROC fails. If table doesnt exist in DB2, the synonmy is not automatically created on database setup. So I just use the above to check if the Synonym exist, and skip that part of the SPROC if the Synonym is not present.

How to check if the Default Value Constraint exists?

I am using SQL server 2008. I need to find if default value constraint does not exist then create it. Here is what I have tried.
IF (NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME ='MyConstraint'))
BEGIN
ALTER TABLE [XX] ADD CONSTRAINT [MyConstraint] DEFAULT ((-1)) FOR [XXXX]
END
GO
if not exists (
select *
from sys.all_columns c
join sys.tables t on t.object_id = c.object_id
join sys.schemas s on s.schema_id = t.schema_id
join sys.default_constraints d on c.default_object_id = d.object_id
where t.name = 'table'
and c.name = 'column'
and s.name = 'schema')
....
I find this to be easier:
IF OBJECT_ID('SchemaName.MyConstraint', 'D') IS NULL
BEGIN
-- create it here
END
I was a bit puzzled as to why this simple task was so complicated. In my case, I don't have constraint names - only table and column names. I want to check if they already have a default before trying to add one.
After a bit more digging, I came up with this:
IF (SELECT Column_Default FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MY_TABLE' AND COLUMN_NAME = 'MY_COLUMN') is NULL
BEGIN
ALTER TABLE [dbo].[MY_TABLE]
ADD DEFAULT ('') FOR [MY_COLUMN]
END
GO
I have to implement this in a ginormous boilerplate script, so the shorter the better.
if not exists(select 1 from sys.default_constraints where name = 'SchemaName.MyConstraint')
begin
-- create it here
end
The following works for me on SQL Server 2016.
Assuming I have a table named MY_TABLE and a column MY_COLIUMN.
I would like to add a constrain (default to '-1' ) on MY_COLIUMN that need to add the constrain on.
/* Test for the specific column */
IF EXISTS (select 1 from sys.all_columns c where c.object_id= OBJECT_ID(N'MY_TABLE') and c.name='MY_COLIUMN')
BEGIN
/* Add default if not exits */
IF NOT EXISTS (
select 1 from sys.default_constraints c where c.object_id =
(
select default_object_id from sys.all_columns c where c.object_id = OBJECT_ID(N'MY_TABLE') and c.name='MY_COLIUMN'
)
)
BEGIN
ALTER TABLE MY_TABLE
ADD DEFAULT '-1' FOR MY_COLIUMN;
END
END
GO
I've used the following in the past:
DECLARE #default sysname
SELECT #default = object_name( cdefault ) FROM syscolumns WHERE id = object_id( 'DBO.TABLE' ) AND name = 'COLUMN'
IF ( not #default is null )
BEGIN
...
END
Search the system table where the default costraints of the database are stored, without the schema name:
IF EXISTS(SELECT 1 FROM sys.default_constraints WHERE [name] = 'MyConstraint')
print 'Costraint exists!';
ELSE
print 'Costraint doesn''t exist!';
I know I'm coming to the party late here, but I am a big fan of OBJECTPROPERTY. Here is how to set a default of 1 on a column if the default does not yet exist.
IF (OBJECTPROPERTY(OBJECT_ID('My_constraint_name'),'CnstIsColumn') IS NULL
ALTER TABLE Mytable ADD CONSTRAINT [MY_constraint_name] DEFAULT ((1)) FOR [My_column_name]

Drop table if exist with similar name in two schema

I use this command to drop a table in sql-server 2008
IF EXISTS(SELECT name FROM [DBName]..sysobjects WHERE name = N'TableName' AND xtype='U')
DROP TABLE [DBName].[SchemaName].[TableName];
But now I have 2 tables with same name in different schema:
[DBName].[Schema1].[Members]
And
[DBName].[Schema2].[Members]
So, what is your suggestion for check if exist this tables? How can I check table names with schema?
UPDATE:
OK, there is 3 different answers and all of them worked, so I don't know which one is better, does any one know about use object_id or sys.tables?
IF EXISTS(
SELECT *
FROM [DBName].sys.tables t
JOIN [DBName].sys.schemas s
ON t.SCHEMA_ID = s.schema_id
WHERE
t.name = N'TableName' AND t.type='U'
AND s.NAME = 'SchemaName'
)
DROP TABLE [DBName].[SchemaName].[TableName];
Update:
object_id in sys.tables is the same as object_id in sysobjects for the same table. And is completely the same as function OBJECT_ID returns for the same table name. See the following illustrating examples.
So, you may simplify the query:
IF exists
(
SELECT *
FROM DBName.sys.tables
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND type = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
or in this way:
IF exists
(
SELECT *
FROM DBName.sys.objects
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND type = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
or for sql2000-styled tables:
IF exists
(
SELECT *
FROM DBName..sysobjects
WHERE object_id = OBJECT_ID('[DBName].[SchemaName].[TableName]')
AND xtype = 'U'
)
DROP TABLE [DBName].[SchemaName].[TableName];
Use this:
IF EXISTS
(
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[DBName].[Schema1].[Member]')
AND type in (N'U')
)
PRINT 'Yes'
ELSE
PRINT 'No';
Don't use sysobjects. Use the modern system views in the sys schema (introduced in 2005):
select * from sys.tables
where
schema_id = SCHEMA_ID('Schema1') and
name='tablename'
As soon as you have one "modern" schema in a 2005 or later database, you cannot reliably use sysobjects to match with schemas. If you only have "old" schemas (objects belonging to users and roles), you may be able to query based on user_id.
Wouldn't it be simplest just to:
IF object_id('[schema].[table]') > 0
DROP TABLE [schema].[table]
For non existent tables object_id() returns NULL
For some system tables it returns a negative int

SQL comments on create table on SQL Server 2008

I need to create some pretty big tables in SQL Server 2008. While I do have SQL Server Management Studio (SSMS), I would like to comment the tables and the columns when I create the table. How do I do this?
An example of the query I am running:
CREATE TABLE cert_Certifications
(
certificationID int PRIMARY KEY IDENTITY,
profileID int,
cprAdultExp datetime null
)
I've tried COMMENT'Expiration Date for the Adult CPR' and COMMENT='Expiration Date for the Adult CPR' after the data type, and SQL Server is giving me an error.
This is what I use
/*==============================================================*/
/* Table: TABLE_1 */
/*==============================================================*/
create table TABLE_1 (
ID int identity,
COLUMN_1 varchar(10) null,
COLUMN_2 varchar(10) null,
constraint PK_TABLE_1 primary key nonclustered (ID)
)
go
declare #CurrentUser sysname
select #CurrentUser = user_name()
execute sp_addextendedproperty 'MS_Description',
'This is my table comment',
'user', #CurrentUser, 'table', 'TABLE_1'
go
declare #CurrentUser sysname
select #CurrentUser = user_name()
execute sp_addextendedproperty 'MS_Description',
'This is the primary key comment',
'user', #CurrentUser, 'table', 'TABLE_1', 'column', 'ID'
go
declare #CurrentUser sysname
select #CurrentUser = user_name()
execute sp_addextendedproperty 'MS_Description',
'This is column one comment',
'user', #CurrentUser, 'table', 'TABLE_1', 'column', 'COLUMN_1'
go
declare #CurrentUser sysname
select #CurrentUser = user_name()
execute sp_addextendedproperty 'MS_Description',
'This is column 2 comment',
'user', #CurrentUser, 'table', 'TABLE_1', 'column', 'COLUMN_2'
go
You can put comments on both tables and columns by creating what are called Extended Properties. You can put extended properties at both the table level and column level. This can be done via T-SQL or SSMS.
For example, in T-SQL it looks something like this:
sp_addextendedproperty 'BackColor', 'Red', 'user', '<schema name>', 'table', '<table name', 'column', '<column name>'.
You can read more about it on sp_addextendedproperty (Transact-SQL).
I prefer the GUI when designing tables because I can visualize the layout better. In the GUI designer, one can add a description for the table and columns in the properties window as shown in the image below
There are good answers in this post. Adding that the value 'MS_Description' could be other thing. For example, we can use 'SourceDescription' for details about the source the data, 'TableDescription' for table and 'ColumnDescription' for each column on table.
Example:
-- Create example table
create table testTablename(
id int,
name varchar(20),
registerNumber bigint
)
-- SourceDescription
EXEC sys.sp_addextendedproperty
#name=N'SourceDescription',
#value=N'Result of process x union y ' , -- Comment about the source this data.
#level0type=N'SCHEMA',
#level0name=N'dbo',
#level1type=N'TABLE',
#level1name=N'testTableName' -- Name of Table
-- TableDescription
EXEC sys.sp_addextendedproperty
#name=N'TableDescription',
#value=N'Table is used for send email to clients.' , -- Coment about the used of table
#level0type=N'SCHEMA',
#level0name=N'dbo',
#level1type=N'TABLE',
#level1name=N'testTableName'
-- ColumnDescription
EXECUTE sp_addextendedproperty
#name = 'ColumnDescription',
#value = 'Unique identification of employer. Its the registry of company too.',
#level0type = 'SCHEMA',
#level0name= N'dbo',
#level1type = N'TABLE',
#level1name = N'testTableName',
#level2type = N'COLUMN',
#level2name = N'registerNumber'
-- If necessary, you can delete the comment.
exec sp_dropextendedproperty
#name = 'ColumnDescription',
#level0type = 'SCHEMA',
#level0name= N'dbo',
#level1type = N'TABLE',
#level1name = N'testTableName',
#level2type = N'COLUMN',
#level2name = N'registerNumber'
-- Show you the table resume
select
tables.name tableName,
tables.create_date,
tables.modify_date,
tableDesc.value TableDescription,
sourceDesc.value SourceDescription
from
sys.tables
left join sys.extended_properties tableDesc on tables.object_id = tableDesc.major_id and tableDesc.name = 'TableDescription'
left join sys.extended_properties sourceDesc on tables.object_id = sourceDesc.major_id and sourceDesc.name = 'SourceDescription'
where
tableDesc.name in('TableDescription', 'SourceDescription', 'ColumnDescription')
order by tables.name
-- show you the columns resume
select
tables.name tableName,
columns.name columnName,
extended_properties.value
from
sys.tables
inner join sys.columns on tables.object_id = columns.object_id
left join sys.extended_properties on
tables.object_id = extended_properties.major_id
and columns.column_id = extended_properties.minor_id
and extended_properties.name in('MS_Description','ColumnDescription')
where
tables.name = 'testTableName'
You need to use the stored procedure called sp_addextendedproperty to add comments to columns/tables in SQL Server.
Although it does not directly answer original question (J Henzel and Randy Minder already did!) I would like to share something else I just wrote that can be very useful for those who have to comment a lot of tables and columns.
The following queries:
-- Generate comments templates for all tables
SELECT
'EXEC sys.sp_addextendedproperty
#name=N''TableDescription'',
#level0type=N''SCHEMA'',
#level1type=N''TABLE'',
#level0name=N''' + TABLE_SCHEMA + ''',
#level1name=N''' + TABLE_NAME + ''',
#value=N''TODO'';'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME NOT like 'sys%'
order by TABLE_SCHEMA, TABLE_NAME
-- Generate comments templates for all columns
SELECT 'EXECUTE sp_addextendedproperty
#name = ''ColumnDescription'',
#level0type = ''SCHEMA'',
#level1type = N''TABLE'',
#level2type = N''COLUMN'',
#level0name=N''' + TABLE_SCHEMA + ''',
#level1name=N''' + TABLE_NAME + ''',
#level2name = N''' + COLUMN_NAME + ''',
#value = ''TODO'';'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA not like 'sys%' and TABLE_NAME not like 'sysdiagrams%'
order by TABLE_SCHEMA, TABLE_NAME, case when ORDINAL_POSITION = 1 then '0' else COLUMN_NAME end
Will produce in SQL Server output a list of calls to sp_addextendedproperty for all the tables and all the columns existing in your database, by querying on system tables to gather them.
Of course, it will not comment it magically for you, but at least you just have to fill the "TODOs" placeholders with the relevant comment for all objects you would like to describe and to execute it.
It avoids you to manually write all the calls and saves a lot of time, and with it you can't forget a table or column, so I hope it will be useful for somebody else.
Side remarks:
Just beware on the filters in WHEREs on "sys": it's here to exclude system objects, but depending on your objects names, you may need a bit of fine-tuning of you have tables named alike.
Also, there isn't any comment at all in my DB, so my query returns all tables/columns. It does not consider whether there's already a comment or not on it.
Use this SQL command:
Create table TABLE NAME (ATTRIBUTE NAME (ATTRIBUTE SIZE)) // Both create and table are keywords

How to identify whether the table has identity column

I want to find out whether the table has an identity column or not. Table is unknown to me. I have not done the structure of the table. Using Query?
I am using Sql Server Compact Edition.
IF (OBJECTPROPERTY(OBJECT_ID('TABLE_NAME'), 'TableHasIdentity') = 1)
ObjectProperty is available starting sql server 2008 Reference:
OBJECTPROPERTY
This query returns a table's identity column name:
CREATE PROCEDURE dbo.usp_GetIdentity
#schemaname nvarchar(128) = 'dbo'
,#tablename nvarchar(128)
AS
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
AND OBJECT_SCHEMA_NAME(object_id) = #schemaname
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
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).
...
declare #tblhasIdentCol bit = IF (IDENT_CURRENT( #dbName +'.'+ #schemaName +'.'+ #tableName ) IS NOT NULL , 1 , 0 )
You get numeric value if table has identity
Very simple answer would be to run this:
SELECT IDENT_CURRENT('TABLE-NAME')
This would give max value of identity column if exists, if the column doesn't exist, it gives 1 as result.
Based on max value, you can identify which column is having that and determine the identity column.
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
CREATE FUNCTION dbo.fnTableHasIdentity(#Tbl sysname)
RETURNS TINYINT
BEGIN
RETURN OBJECTPROPERTY(OBJECT_ID(#Tbl), 'TableHasIdentity')
END
--As simple as that!
select t.name as TableName,c.name as ColumnName
from sys.identity_columns c
inner join sys.tables t on c.object_id = t.object_id
where t.name = 'TableName'
If you like me, needed to be able to do this for tables in an arbitrary database, then I found the following solution:
IF EXISTS (
SELECT 1
FROM [database name].sys.identity_columns AS id_col
INNER JOIN [database name].sys.objects
ON objects.object_id = id_col.object_id
INNER JOIN [database name].sys.schemas
ON schemas.schema_id = objects.schema_id
AND schemas.name = 'schema name'
WHERE OBJECT_NAME(id_col.object_id, DB_ID('database name')) = 'table name'
) SELECT 1 ELSE SELECT 0
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'
One way to list all Tables with their identity column if it exists
to get you desired table add at the end of the filter "and o.name='TableName'"
where Tbale Nam is the table you are looking for
SELECT o.[Name][TableName],i.[name][IdentityColName] FROM
sys.objects o
left outer join sys.identity_columns i on i.object_id=o.object_id
where o.type='U'