Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 How to write a query that checks if a column exists?

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-04-17 : 09:38:01
Ashley writes "Is there any SQL statement I can write to check to see if a column exists within a table without getting an error message? I have tried "exists" and all the other basic stuff I could think of. This is for debugging purposes, and would really shorten the task ahead of me. Thanks!"

leeholden
Starting Member

34 Posts

Posted - 2002-04-17 : 09:50:38
you can query syscolumns (it's documented) to see if it exists.
I'm sure there will be some purists saying that you shouldn't query system tables though.
Go to Top of Page

Nazim
A custom title

1408 Posts

Posted - 2002-04-17 : 09:57:18
Am gulity of quering them lot of times. its better not to as the schema can change in future versions.

INFORMATION_SCHEMA.COLUMNS should help to query for existence of columns.

but Ashley, AFAIK you cant really do that using normal querying. Dynamic Sql should be of good help.







--------------------------------------------------------------
Go to Top of Page

dsdeming

479 Posts

Posted - 2002-04-17 : 12:49:48
This should help:


use northwind
declare @table sysname, @column sysname
set @table = 'Invoices'
set @column = 'CustomerID'

if exists( select * from INFORMATION_SCHEMA.COLUMNS where table_name = @table and column_name = @column)
print 'y'
else
print 'n'

set @column = 'foo'

if exists( select * from INFORMATION_SCHEMA.COLUMNS where table_name = @table and column_name = @column)
print 'y'
else
print 'n'

Go to Top of Page
   

- Advertisement -