Rakesh C S
Rakesh C S

Reputation: 21

SQL Server stored procedure error handling with if exists

I have five databases, In that three databases having column Countries and two databases having column Countryrelease..

I am using a cursor, so if I use exists that particular column is throwing an error that column not exists how to handle this one.

Syntax

if exists(select 1 from table where column name='Countries')
    select do some operation
else
    select do some operation

Upvotes: 0

Views: 193

Answers (1)

Skin
Skin

Reputation: 11277

You want to make use of the meta data within the SQL instance.

This will work for you ...

if (SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'YourTableName' AND COLUMN_NAME = 'Countries') = 1
    -- The "Countries" column exists
    select do some operation
else
    select do some operation

Upvotes: 1

Related Questions