I have a long script and I like to be able to just run the whole file when I need to and not worry about if parts of it have already ran. But the script below is giving me probl
Martin was definitely onto something. The stuff inside the IF
is being treated by the parser at parse time and ignoring whether your IF
will pan out. This is the same reason you can't do:
IF 1 = 1
CREATE TABLE #x(a INT);
ELSE
CREATE TABLE #x(b INT);
One workaround would be to use dynamic SQL:
IF EXISTS ...
BEGIN
BEGIN TRANSACTION;
DECLARE @sql NVARCHAR(MAX);
SET @sql = N'
DELETE FROM [dbo].[Notes]
WHERE [EntityId] IS NULL
AND [EntityType] IS NULL
--Delete notes where the corresponding contact or account has been deleted.
OR [ID] IN (9788, 10684, 10393, 10718, 10719)
--Populate new columns with all existing data
UPDATE [dbo].[Notes]
SET [AccountId] = [EntityId]
WHERE [EntityType] = 1
UPDATE [dbo].[Notes]
SET [ContactId] = [EntityId]
WHERE [EntityType] = 2
--Delete EntityId and EntityType columns from the Notes table
ALTER TABLE [dbo].[Notes]
DROP COLUMN [EntityId], [EntityType]';
EXEC sp_executesql @sql;
COMMIT TRANSACTION;
END
But you still should be sure that both columns are there.