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
 Transact-SQL (2000)
 Finding if a field exists

Author  Topic 

brandonl
Yak Posting Veteran

58 Posts

Posted - 2003-03-19 : 13:04:28
I have a query that normally look slike the following:

SELECT column1, column2, column3, column4 FROM table

I pull this table from multiple servers daily, the problem is that not all servers have the column2 field. How do it write the sql statment so that if column2 does not exist in that table, it will change column2 to: '' AS column2 into the statement?


~BrandonL

yakoo
Constraint Violating Yak Guru

312 Posts

Posted - 2003-03-19 : 13:23:44
Im not sure if there is a way to do it in one statement but you might be able to take advantage of the COL_NAME function which allows you to specify the object (your table) and the index of your column.

Got SQL?
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2003-03-19 : 13:29:26
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'table' AND column_name = 'column2')
SELECT column1, column2, column3, column4
FROM table
ELSE
SELECT column1, '' AS column2 column3, column4
FROM table

Tara
Go to Top of Page

nr
SQLTeam MVY

12543 Posts

Posted - 2003-03-19 : 13:41:22
You will probably need
declare @sq varchar(1000)
IF EXISTS (SELECT * FROM information_schema.columns WHERE table_name = 'table' AND column_name = 'column2')
select @sql = 'SELECT column1, column2, column3, column4
FROM table'
ELSE
select @sql = 'SELECT column1, '''' AS column2 column3, column4
FROM table'

exec (@sql)

Depends how you execute the remote server select.

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page
   

- Advertisement -