kormie 0 Newbie Poster

I have "inherited" a series of scripts which are designed to run in SQL Query Analyzer to incrementally update a database based on a version id stored in a table. Each script includes code to create new tables, alter existing columns, add or swap out triggers, grant permissions, update data, etc. I am trying to preface this code with some simple error proofing to verify the selected database has the version table and is at the correct version for the script – ie, if the at v1, only the script that updates v1 to v2 should be executed.

The basic logic is:

-- variable to indicate whether OK to update
declare @UpdateDB int
SET @UpdateDB = 0

-- check to see is version table exists
if not exists (select …)
begin
code for …the selected file is not a valid…
end
else
-- check current version
begin
code to get version …
if @DBVersion = xxx
begin
code for …database is at latest version…
end
else
if @ DBVersion >= yyy
begin
code for …proceed to next script…
end
else
if @contents <= zzz
begin
code for …run previous script first…
end
else
-- OK to update
SET @UpdateDB = 1
end
end

if @UpdateDB = 0
begin
code for ...not updating...
end
else

code for ...UPDATE...


My problem is avoiding the update code if the validation fails. If I don’t have the update code within a begin…end, only the first command is skipped, and the rest of the script executes. The update code consists of several thousand lines with hundreds of begin…end sections followed by "GO" statements. If I try to bracket the entire thing in a begin…end, the "GO" statements cause errors – as does simply removing the "GO" statements. Using a "RETURN" after the code for ...not updating... has no effect and without having a begin…end a "GOTO" isn’t possible. What am I missing?

Thanks for any insight.