How can I tell if a column for a table already exists?   Leave a comment

Below are the two ways in SQL server to identify whether column in a particular table Exists or Not.

Create Table Employee (ID int, Name varchar(100))
GO

--Way 1

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employee' AND COLUMN_NAME = 'Name')
BEGIN
		PRINT 'EXISTS'
END
ELSE
BEGIN
		PRINT 'DOESN''T EXISTS'
END

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Employee' AND COLUMN_NAME = 'Adress')
BEGIN
		PRINT 'EXISTS'
END
ELSE
BEGIN
		PRINT 'DOESN''T EXISTS'
END

--Way 2
if columnproperty (object_id('Employee'), 'Name', 'AllowsNull') IS NOT NULL
BEGIN
		PRINT 'EXISTS'
END
ELSE
BEGIN
		PRINT 'DOESN''T EXISTS'
END

if columnproperty (object_id('Employee'), 'Address', 'AllowsNull') IS NOT NULL
BEGIN
		PRINT 'EXISTS'
END
ELSE
BEGIN
		PRINT 'DOESN''T EXISTS'
END
Advertisements

Posted December 4, 2014 by Izharuddin Shaikh in SQL

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: