1

I am trying to turn this SQL example command into a C # SqlCommand:

if not exists (select column_name
               from INFORMATION_SCHEMA.columns
               where table_name = 'TotalHeals'
                 and column_name = '"+Healee+"')
    alter table TotalHeals add +Healee+ int

What I have so far

// TO DO check to see if column exists instead of throwing error
cmd2 = new SqlCommand("ALTER TABLE TotalHeals ADD " + Healee + " INT",openCon);
cmd2.ExecuteNonQuery();

I am completely lost how to code the if not exists statement. Any help?

1
  • I am dynamically adding columns on the fly and do not want to just catch the exception when the column already exists Commented May 23, 2016 at 3:17

1 Answer 1

1

You need to execute your first select query to check whether the column exist like this

cmd = new SqlCommand("Select count(*) from
                     INFORMATION_SCHEMA.columns
                     where
                     table_name = 'TotalHeals'
                     and column_name = '"+Healee+"',openCon);
int output=Convert.ToInt32(cmd.ExecuteScalar());

if (output>0)
 // column already present....handle that case..
else
//alter your table to add the column
Sign up to request clarification or add additional context in comments.

4 Comments

I am throwing a Exception thrown: 'System.FormatException' in mscorlib.dll on the int output=Convert.ToInt32(cmd.ExecuteScalar()); line
are you doing select count(*) ?
Caught your code mid edit... testing the updated version
Thank you very much for the help! I had to change this '"+Healee+"'",openCon);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.