I'm told to make some changes to the schema of our database, so I wrote the following script that does the following:
- Update the value of the table, according the the value of another table
- Delete the column that contains the id pointing to the other table
The entire script should only be executed if the id_to_other_table exists of course
Here is my SQL
IF EXISTS (
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'title_id' AND TABLE_NAME = 'my_table'
)
BEGIN
UPDATE
my_table
SET
my_table.title = other_table.value
FROM
my_table
INNER JOIN
other_table
ON
my_table.title_id = other_table.id
WHERE other_table.language_id = 1 --hardcoded
ALTER TABLE my_table
DROP COLUMN title_id
END
The first time I run this SQL, the code is executed properly. When I run it once more, instead of doing nothing, it gives me the following error, pointing to the line after the ON part of the JOIN:
Invalid column name 'my_table.title_id'
If I replace the contents of the BEGIN - END block with print "Does the column exists?" it correctly displays nothing, so the BEGIN - END block is ending preemptively for some reason...
Any ideas?
title_idafter dropping it?