Monday, March 19, 2012

Check for column & insert

Can you tell me if this is possible? (and how to do it!!)

The application is VS2005, with sql database.

I want to check if a specific column exists in a specific table in the database and if not then add it, all via my application.

I'm happy knowing how to connect to the database & pass sql commands (as I'm doing that anyway to set off backups), but not the actual queries I'd need.

Hi,

Yes it is possible. This is an example (SQL 2005) that adds the column NewColumn to the Person.Contact table (AdventureWorks) if the column does not exists.

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Person'
AND TABLE_NAME = 'Contact'
AND COLUMN_NAME = 'NewColumn')
BEGIN
ALTER TABLE Person.Contact
ADD NewColumn int
END

Greetz,

Geert

Geert Verhoeven
Consultant @. Ausy Belgium

My Personal Blog

|||

Great thanks,

got that working now...

No comments:

Post a Comment