1

I know very little SQL, but found a command for SQL Server to add a column to the database if it doesn't already exist. Sadly it doesn't work when executed against my MySQL database, returning a syntax error.

$query = $dbh->prepare("if not exists (select * from syscolumns where id=object_id(':table_name') and name='where') alter table :table_name add where int(2)");

if($query->execute(array(':table_name'=>'registrations'))) {
    //twist and shout
} else {
    print_r($query->errorInfo());   
}

So what should I change to create the column 'where int(2)' if it doesn't exist?

3
  • why do you need dynamically create a column? Commented Mar 30, 2011 at 18:37
  • 1
    You should avoid using reserved words (like WHERE) as column names. Commented Mar 30, 2011 at 18:41
  • Excellent point, I need to change that to something safer and more descriptive. I have do this via a PHP script because it's the only way I know how with the level of access I have, I can't access the database server directly. Commented Mar 30, 2011 at 19:48

1 Answer 1

1

You would have to create a stored procedure to handle this within one statement. This was discussed here: add column to mysql table if it does not exist

Sign up to request clarification or add additional context in comments.

1 Comment

Just do it and catch the resulting error. It's not how I like to work, but it's late and this needs a fix, so thank you!

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.