guys i am totally newbie .. what i want is to delete a column in table only if it exists ... any help
here is what i know ALTER TABLE MEN DROP COLUMN Lname
but how to make if it exists only in sql ??
The column Extension existing in the refreshed list is verification that it exists. To drop the Extensions column, we simply right click on it and delete as before.
The name of the default constraint might have been automatically generated and hard to predict, so you need to look up the default constraint name first, and then drop the column. Just replace __TableName__ and __ColumnName__ with the appropriate values.
ALTER TABLE is used to add, delete/drop or modify columns in the existing table. It is also used to add and drop various constraints on the existing table.
Fixed the syntax error in mIhAwk's answer:
if (exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'mytable' AND COLUMN_NAME = 'mycolumn'))
begin
ALTER TABLE mytable DROP COLUMN mycolumn
end
What you want to do is not possible in pure MySQL-syntax. However, if you are using a API or something as back-end in a application. You can do the following.
IF (SELECT COUNT(*)
FROM table_name.columns
WHERE
TABLE_SCHEMA = 'database_name'
AND TABLE_NAME = 'table_name'
AND COLUMN_NAME = 'column_name'>0)
BEGIN
ALTER TABLE table_name DROP COLUMN column_name
END
Below code solve your problem.
if (exists (SELECT * FROM information_schema.COLUMNS WHERE TABLE_NAME = 'mytable' AND COLUMN_NAME = 'mycolumn'))
begin
ALTER TABLE 'mytable' DROP COLUMN 'mycolumn'
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With