Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How can I check if column exists?

Status
Not open for further replies.

vladibo

Programmer
Sep 14, 2003
161
CA
How can I check inside a T-SQL script if column exists?
 
Through system tables or information_schema view:
Code:
if exists( select * from sysobjects A inner join syscolumns B on A.id=B.id where A.name='table_name' and B.name='column_name')
	print ('exists')

if exists( select * from information_schema.columns where table_name = 'table_name' and column_name='column_name' )
	print ('exists')
 
Here is a piece of code that will allow you to specify a column that you are looking for and tell you all the tables that the column appers in.

CREATE PROCEDURE [spColumnsInTableNew] @columnName varchar(50)

AS

select sc.name as ColumnName, so.name as TableName
from syscolumns as SC inner join sysobjects as SO on SC.id = SO.id
where sc.name = @columnName
AND so.xtype = 'U'
Order By so.name


Ex SpColumnsInTableNew 'FirstName' (this will return every table that the name of the column 'FirstName' exists.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top