27

How do I check if a column exists in SQL Server 2000?

Alexander Prokofyev
  • 33,874
  • 33
  • 95
  • 118
user31071
  • 271
  • 1
  • 3
  • 4
  • 2
    possible duplicate of [How to check if column exists in SQL Server table](http://stackoverflow.com/questions/133031/how-to-check-if-column-exists-in-sql-server-table) – Danny Varod Dec 11 '11 at 19:16

5 Answers5

39
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_NAME='tablename' AND COLUMN_NAME='columname' )
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
9
If col_length('table_name','column_name') is null
    select 0 as Present
ELSE
    select 1 as Present

Present will be 0, is there is no column_name present in table_name , otherwise 1

@CMS: I don't think that 'INFORMATION_SCHEMA.COLUMNS' have information about every table in DB. Because this didn't worked for me. But my answer did worked.

Deepak Yadav
  • 1,724
  • 3
  • 23
  • 38
5

In query analyzer, select the Database that contains the table in which you need to check if the field exists or not and run the query below.

SELECT count(*) AS [Column Exists] 
FROM SYSOBJECTS  
INNER JOIN SYSCOLUMNS ON SYSOBJECTS.ID = SYSCOLUMNS.ID 
WHERE 
 SYSOBJECTS.NAME = 'myTable' 
 AND SYSCOLUMNS.NAME = 'Myfield'
Soumya
  • 13,677
  • 6
  • 34
  • 49
user20358
  • 14,182
  • 36
  • 114
  • 186
2

This should do nicely:

if COLUMNPROPERTY(object_id('table_name'), 'column_name', 'ColumnId') is null
  print 'doesn\'t exist'
else
  print 'exists'
Soumya
  • 13,677
  • 6
  • 34
  • 49
Dan
  • 21
  • 1
0

I don't know if this script will work in sqlserver 2000, but in 2008 works:

SELECT COLUMNS.*
FROM INFORMATION_SCHEMA.COLUMNS COLUMNS, INFORMATION_SCHEMA.TABLES TABLES
WHERE COLUMNS.TABLE_NAME=TABLES.TABLE_NAME AND UPPER(COLUMNS.COLUMN_NAME)=UPPER('column_name')
animuson
  • 53,861
  • 28
  • 137
  • 147
Douglas Tondo
  • 219
  • 2
  • 2