"sp_spaceused" returns not uptodate numbers - sql-server-express

We use "sp_spaceused" in a while-loop where we delete data.
We do so in order to remain under the 10GB SQL Express Edition limit.
The Delete routine that runs nightly
PROCEDURE [dbo].[DeletePeriod4Data]
#LIMIT_InMB AS FLOAT
AS
BEGIN
SET NOCOUNT ON
DECLARE #MinBegin AS DATETIME
DECLARE #SizePeriod4_InMB AS FLOAT
EXEC [dbo].[GetDatabaseStatsPeriod4MB]
#Size_InMB = #SizePeriod4_InMB OUTPUT
WHILE #SizePeriod4_InMB > #LIMIT_InMB
BEGIN
SELECT #MinBegin = MIN(MONTH.ProdData.[Begin])
FROM MONTH.ProdData
PRINT 'deleting from period 4, month and year of: '
PRINT #MinBegin
DELETE
FROM Month.ProdData
WHERE
Year = DATEPART(YEAR, #MinBegin)
AND
Month = DATEPART(MONTH, #MinBegin)
EXEC [GetDatabaseStatsPeriod4MB]
#Size_InMB = #SizePeriod4_InMB OUTPUT
END
END
And this is the culprit stored procedure that returns outofdate numbers.
PROCEDURE [dbo].[GetDatabaseStatsPeriod4MB]
#Size_InMB float OUTPUT
AS
BEGIN
CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18),
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))
DBCC UPDATEUSAGE(0); -- <-- helps?
EXEC sp_msforeachtable #command1=
'INSERT INTO #t EXEC sp_spaceused ''?'', #updateUsage=''TRUE''',
#whereand=' and schema_name(schema_id) = ''Month'' '
SELECT #Size_InMB =
SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)))/1024.0
FROM #t
DROP TABLE #t
PRINT 'PERIODE 4 Size (Month)'
PRINT #Size_InMB
END
What we tried is
Adding parameter "#updateUsage=TRUE" to sp_spaceused
Added call to "DBCC UPDATEUSAGE(0);"
Added params to "DBCC UPDATEUSAGE(0) WITH NO_INFOMSGS, COUNT_ROWS;"
Using a delay before I call “UpdateUsage”
WAITFOR DELAY '00:00:05' ---- 5 Second Delay
Generic code to repro the problem
CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18),
data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))
EXEC sp_msforeachtable #command1=
'INSERT INTO #t EXEC sp_spaceused ''?'', #updateUsage=''TRUE'''
SELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)))/1024.0
FROM #t
DROP TABLE #t
-- Delete something in your DB (Northwind)
-- Run the above again

You need to allow for time for Ghost Cleanup to handle the ghosted records since DELETE doesn't actually delete anything, it just marks the records as ghosted in the slot on the page and then it is the job of the Ghost Cleanup task to clean those up later. You can read about this in Paul's blog posts:
Inside the Storage Engine - Ghost Cleanup in Depth
Ghost Cleanup - Redux
Truning off the Ghost Cleanup Task for a Performance Gain
You can also track Ghost Cleanup activity with Extended Events in SQL Server 2008+ as I show in my blog post:
Tracking Ghost Cleanup
You either need to wait between the delete and checking for space used to allow Ghost Cleanup to run or between the delete and the check for space used, force Ghost Cleanup by forcing an index scan as Paul explains in his blog posts.

Related

Dynamically iterate through passed in parameter-value(s) in T-SQL procedure

I'm currently trying to write a default procedure template for reporting from a T-SQL Datawarehouse.
The idea is to wrap each query in a procedure, so that permissions and logging can be managed easily.
Since this will be done by the DBAs, I would like to have this solution work by only pasting some standard code before and after the main query. I'd prefer if the DBA didn't have to modify any part of the logging-code.
I've solved this for most parts, however, I need to log which parameters the user has submitted to the procedure.
The obvious solution would be hardcode the parameters into the logging. However, the procedures can have a varying amount of parameters, and I'd therefore like a catch-all solution.
My understanding is that there is no easy way iterating through all parameters.
I can however access the parameter-names from the table sys.parameters.
The closest to a solution I've come, is this minimal example:
CREATE TABLE #loggingTable (
[ProcedureID] INT
, [paramName] NVARCHAR(128)
, [paramValue] NVARCHAR(128)
)
;
go
CREATE PROCEDURE dbo.[ThisIsMyTestProc] (
#param1 TINYINT = NULL
, #Param2 NVARCHAR(64) = null
)
AS
BEGIN
-- Do some logging here
DECLARE #query NVARCHAR(128)
DECLARE #paramName NVARCHAR(128)
DECLARE #paramValue nvarchar(128)
DECLARE db_cursor CURSOR FOR
SELECT [name] FROM [sys].[parameters] WHERE object_id = ##PROCID
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO #paramName
WHILE ##FETCH_STATUS = 0
BEGIN
SET #query = 'SELECT #paramValue = cast(' + #paramName + ' as nvarchar(128))';
SELECT #query;
-- Following line doesn't work due to scope out of bounds, and is prone to SQL-Injections.
--EXEC SP_EXECUTESQL #query; -- Uncomment for error
insert into #loggingTable(ProcedureID, paramName, paramValue)
values(##PROCID, #paramName, #paramValue)
FETCH NEXT FROM db_cursor INTO #paramName
END
CLOSE db_cursor
DEALLOCATE db_cursor
-- Run the main query here (Dummy statement)
SELECT #param1 AS [column1], #Param2 AS [column2]
-- Do more logging after statement has run
END
GO
-- test
EXEC dbo.[ThisIsMyTestProc] 1, 'val 2';
select * from #loggingTable;
-- Cleanup
DROP PROCEDURE dbo.[ThisIsMyTestProc];
DROP table #loggingTable;
However, this does have to major drawbacks.
It doesn't work due to variable scopes
It is prone to SQL-Injections, which is unacceptable
Is there any way to solve this issue?
The values of the parameters are not availiable in a generic approach. You can either create some code generator, which will use sys.parameters to create a chunk of code you'd have to copy into each of your SPs, or you might read this or this about tracing and XEvents. The SQL-Server-Profiler works this way to show you statements together with the parameter values...
If you don't want to get into tracing or XEvents you might try something along this:
--Create a dummy proc
CREATE PROCEDURE dbo.[ThisIsMyTestProc] (
#param1 TINYINT = NULL
, #Param2 NVARCHAR(64) = null
)
AS
BEGIN
SELECT ##PROCID;
END
GO
--call it to see the value of ##PROCID
EXEC dbo.ThisIsMyTestProc; --See the proc-id
GO
--Now this is the magic part. It will create a command, which you can copy and paste into your SP:
SELECT CONCAT('INSERT INTO YourLoggingTable(LogType,ObjectName,ObjectId,Parameters) SELECT ''ProcedureCall'', ''',o.[name],''',',o.object_id,','
,'(SELECT'
,STUFF((
SELECT CONCAT(',''',p.[name],''' AS [parameter/#name],',p.[name],' AS [parameter/#value],''''')
FROM sys.parameters p
WHERE p.object_id=o.object_id
FOR XML PATH('')
),1,1,'')
,' FOR XML PATH(''''),ROOT(''parameters''),TYPE)'
)
FROM [sys].[objects] o
WHERE o.object_id = 525244926; --<-- Use the proc-id here
--Now we can copy the string into our procedure
--I out-commented the INSERT part, the SELECT is enough to show the effect
ALTER PROCEDURE dbo.[ThisIsMyTestProc] (
#param1 TINYINT = NULL
, #Param2 NVARCHAR(64) = null
)
AS
BEGIN
--The generated code comes in one single line
--INSERT INTO YourLoggingTable(LogType,ObjectName,ObjectId,Parameters)
SELECT 'ProcedureCall'
,'ThisIsMyTestProc'
,525244926
,(SELECT'#param1' AS [parameter/#name],#param1 AS [parameter/#value],''
,'#Param2' AS [parameter/#name],#Param2 AS [parameter/#value],''
FOR XML PATH(''),ROOT('parameters'),TYPE)
END
GO
Hint: We need the empty element (,'') at the end of each line to allow multiple elements with the same name.
--Now we can call the SP with some param values
EXEC dbo.ThisIsMyTestProc 1,'hello';
GO
As a result, your Log-Table will get an entry like this
ProcedureCall ThisIsMyTestProc 525244926 <parameters>
<parameter name="#param1" value="1" />
<parameter name="#Param2" value="hello" />
</parameters>
Just add typical logging data like UserID, DateTime, whatever you need...
Scope is the killer issue for this approach. I don't think there's a way to reference the values of parameters by anything but their variable names. If there was a way to retrieve variable values from a collection or by declared ordinal position, it could work on the fly.
I understand wanting to keep the overhead for the DBAs low and eliminating opportunities for error, but I think the best solution is to generate the required code and supply it to the DBAs or give them a tool that generates the needed blocks of code. That's about as lightweight as we can make it for the DBA, but I think it has the added benefit of eliminating processing load in the procedure by turning it into a static statement with some conditional checking for validity and concatenation work. Cursors and looping things should be avoided as much as possible.
Write a SQL script that generates your pre- and post- query blocks. Generate them in mass with a comment at the top of each set of blocks with the stored procedure name and hand it to the DBAs to copy/paste into the respective procs. Alternatively, give them the script and let them run it as needed to generate the pre- and post- blocks themselves.
I would include some checks in the generated script to help make sure it works during execution. This will detect mismatches in the generated code due to subsequent modifications to the procedure itself. We could go the extra mile and include the names of the parameters when the code is generated and verify them against sys.parameters to make sure the parameter names hard-coded into the generated code haven't changed since code generation.
-- Log execution details pre-execution
IF object_name(##PROCID) = 'ThisIsMyTestProc' AND (SELECT COUNT(*) FROM [sys].[parameters] WHERE object_id = ##PROCID) = 2
BEGIN
EXEC LogProcPreExecution #Params = CONCAT('parm1: ', #param1, ' parm2: ', #Param2), #ProcName = 'ThisIsMyTestProc', #ExecutionTime = getdate() #ExecutionUser = system_user
END
ELSE
BEGIN
--Do error logging for proc name and parameter mismatch
END
--Log procedure would look like this
CREATE PROCEDURE
LogProcPreExecution
#Parameters varchar(max),
#ProcName nvarchar(128),
#ExecutionTime datetime,
#ExecutionUser nvarchar(50)
AS
BEGIN
--Do the logging
END

Sql Server 2008 Clear Select statement cache?

Is there any possible that having a cache clear after performed a select statement?
I tried with one of my sql that at first time i execute it, its return me 3.15 minutes and second time(dint change any stuff) its return me 2.55 minutes.
Its is kind of tedious for me to test out the actual performance on the sql.
I found there is having cache on Sql Server 2005 on this post.
Am i correct about the cache having on sql server 2008?
This is what I do for the same purpose:
DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS
GO
DROP TABLE [WHATEVER I NEED TO DROP]
GO
TRUNCATE TABLE [WHATEVER I NEED TO EMPTY]
GO
UPDATE [WHATEVER HAS TO BE "RESET"]
GO
[DO REST OF "RESET ACTIONS" HERE]
USE [YOUR DATABASE NAME]
GO
DECLARE #start_time datetime, #end_time datetime, #miliseconds int
DECLARE #ALL_YOUR_VARS -- _YOU'LL_USE_WHILE_YOU_MEASURE
/* BECAUSE YOU DON'T WANT TO MEASURE THE TIME SPENT ON TEMP VARS YOU CREATE FOR MEASURING EXEC TIME ONLY */
-- TODO: SET VARS' VALUES HERE, SAME REASON AS ABOVE
SET #start_time = GETDATE()
-- [EXECUTE ALL YOUR STATEMENTS HERE]
-- [YOU WANT TO MEASURE]
SET #end_time = GETDATE()
SET #miliseconds = DATEDIFF(ms, #start_time, #end_time)
SELECT #start_time, #end_time, CAST(#miliseconds AS VARCHAR(max)) + ' ms'
GO
EDIT: Almost forgot! You can also drop all active connections to your DB before start measuring (don't forget to create a new connection after you execute the code below as actual immediate window, from which you run the query will get disconnected too!!!)USE master
GO
SET NOCOUNT ON
DECLARE #DBName varchar(50)
DECLARE #spidstr varchar(8000)
DECLARE #ConnKilled smallint
SET #ConnKilled=0
SET #spidstr = ''
Set #DBName = 'YOURDBNAMEHERE'
IF db_id(#DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT #spidstr=coalesce(#spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(#DBName)
IF LEN(#spidstr) > 0
BEGIN
EXEC(#spidstr)
SELECT #ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(#DBName)
END

How to see progress of running SQL stored procedures?

Consider the following stored procedure..
CREATE PROCEDURE SlowCleanUp (#MaxDate DATETIME)
AS
BEGIN
PRINT 'Deleting old data Part 1/3...'
DELETE FROM HugeTable1 where SaveDate < #MaxDate
PRINT 'Deleting old data Part 2/3...'
DELETE FROM HugeTable2 where SaveDate < #MaxDate
PRINT 'Deleting old data Part 3/3...'
DELETE FROM HugeTable3 where SaveDate < #MaxDate
PRINT 'Deleting old data COMPLETED.'
END
Let's say that each delete statement take a long time to delete, but I like to see the progress of this stored procedure when I'm running it in SQL Management Studio. In other words, I like to see the the output of the PRINT statements to see where I'm at any given time. However, it seems that I can only see the PRINT outputs at the end of the ENTIRE run. Is there a way to make it so that I can see the PRINT outputs at real time? If not, is there any other way I can see the progress of a running stored procedure?
If you use RAISERROR with a severity of 10 or less, and use the NOWAIT option, it will send an informational message to the client immediately:
RAISERROR ('Deleting old data Part 1/3' , 0, 1) WITH NOWAIT
Yes you should be able to get the message to print immediately if you use RAISERROR:
RAISERROR('Hello',10,1) WITH NOWAIT
I have found a great NON-INTRUSIVE way to see the progress of along running stored procedure. Using code I found on Stackoverflow of SP_WHO2, you can see the first column has the current code actually being run from the PROC. Each time you re-run this SP_Who2 process, it will display the code running at the time.This will let u know how far along your proc is at anytime. Here is the sp_who2 code which I modified to make it easier to track progress:
Declare #loginame sysname = null
DECLARE #whotbl TABLE
(
SPID INT NULL
,Status VARCHAR(50) NULL
,Login SYSNAME NULL
,HostName SYSNAME NULL
,BlkBy VARCHAR(5) NULL
,DBName SYSNAME NULL
,Command VARCHAR(1000) NULL
,CPUTime INT NULL
,DiskIO INT NULL
,LastBatch VARCHAR(50) NULL
,ProgramName VARCHAR(200) NULL
,SPID2 INT NULL
,RequestID INT NULL
)
INSERT INTO #whotbl
EXEC sp_who2 #loginame = #loginame
SELECT CommandText = sql.text ,
W.*
,ExecutionPlan = pln.query_plan
,ObjectName = so.name
,der.percent_complete
,der.estimated_completion_time
--,CommandType =der.command
FROM #whotbl W
LEFT JOIN sys.dm_exec_requests der
ON der.session_id = w.SPID
OUTER APPLY SYS.dm_exec_sql_text (der.sql_handle) Sql
OUTER APPLY sys.dm_exec_query_plan (der.plan_handle) pln
LEFT JOIN sys.objects so
I wish I remember who I got this original code from, but it has been VERY helpful. It also identifies the SPID if I need to kill a process.

stored procedure running continuosly in background

I am using one class file for updating my tables. In that I am either inserting or updating tables and after each update or insert, I am calling one stored procedure to save the last updated ID of the table. But once this stored procedure runs it never releases the resource. It is executing always in background. Why is this happening and how can I stop it?
Here is the stored procedure:-
Create procedure [dbo].[Updlastusedkey]
(
#tablename varchar(50)
)
as
Begin
DECLARE #sql varchar(300)
SET #SQL='UPDATE primarykeyTab SET lastKeyUsed = ISNULL(( SELECT Max(ID) from '+#tablename +'),1) WHERE Tablename='''+#tablename +''''
print #SQL
EXEC(#SQL)
END
Do you have Auto-Commit turned on? I think implicit_transactions = OFF means Auto Commit = ON in SQL Server. If not your Update operation may not be executing a COMMIT for the transaction it opened so leaving a write lock on the table. Alternatively just explicitly COMMIT your update perhaps.
Why don't you just create a view?
CREATE VIEW dbo.vPrimaryKeyTab
AS
SELECT tablename = 'table1', MAX(id_column) FROM table1
UNION
SELECT tablename = 'table2', MAX(id_column) FROM table2
/* ... */
;
Now you don't need to update anything or run anything in the background, and the view is always going to be up to date (it won't be the fastest query in the world, but at least you only pay that cost when you need that information, rather than constantly keeping it up to date).
Try this -
UPDATE primarykeyTab SET lastKeyUsed = ISNULL(( SELECT Max(ID) from '+#tablename
+' WITH (NOLOCK)),1) WHERE Tablename='''+#tablename +'''' WITH (NOLOCK)

Is there a way to persist a variable across a go?

Is there a way to persist a variable across a go?
Declare #bob as varchar(50);
Set #bob = 'SweetDB';
GO
USE #bob --- see note below
GO
INSERT INTO #bob.[dbo].[ProjectVersion] ([DB_Name], [Script]) VALUES (#bob,'1.2')
See this SO question for the 'USE #bob' line.
Use a temporary table:
CREATE TABLE #variables
(
VarName VARCHAR(20) PRIMARY KEY,
Value VARCHAR(255)
)
GO
Insert into #variables Select 'Bob', 'SweetDB'
GO
Select Value From #variables Where VarName = 'Bob'
GO
DROP TABLE #variables
go
The go command is used to split code into separate batches. If that is exactly what you want to do, then you should use it, but it means that the batches are actually separate, and you can't share variables between them.
In your case the solution is simple; you can just remove the go statements, they are not needed in that code.
Side note: You can't use a variable in a use statement, it has to be the name of a database.
I prefer the this answer from this question
Global Variables with GO
Which has the added benefit of being able to do what you originally wanted to do as well.
The caveat is that you need to turn on SQLCMD mode (under Query->SQLCMD) or turn it on by default for all query windows (Tools->Options then Query Results->By Default, open new queries in SQLCMD mode)
Then you can use the following type of code (completely ripped off from that same answer by Oscar E. Fraxedas Tormo)
--Declare the variable
:setvar MYDATABASE master
--Use the variable
USE $(MYDATABASE);
SELECT * FROM [dbo].[refresh_indexes]
GO
--Use again after a GO
SELECT * from $(MYDATABASE).[dbo].[refresh_indexes];
GO
If you are using SQL Server you can setup global variables for entire scripts like:
:setvar sourceDB "lalalallalal"
and use later in script as:
$(sourceDB)
Make sure SQLCMD mode is on in Server Managment Studi, you can do that via top menu Click Query and toggle SQLCMD Mode on.
More on topic can be found here:
MS Documentation
Temp tables are retained over GO statements, so...
SELECT 'value1' as variable1, 'mydatabasename' as DbName INTO #TMP
-- get a variable from the temp table
DECLARE #dbName VARCHAR(10) = (select top 1 #TMP.DbName from #TMP)
EXEC ('USE ' + #dbName)
GO
-- get another variable from the temp table
DECLARE #value1 VARCHAR(10) = (select top 1 #TMP.variable1 from #TMP)
DROP TABLE #TMP
It's not pretty, but it works
Create your own stored procedures which save/load to a temporary table.
MyVariableSave -- Saves variable to temporary table.
MyVariableLoad -- Loads variable from temporary table.
Then you can use this:
print('Test stored procedures for load/save of variables across GO statements:')
declare #MyVariable int = 42
exec dbo.MyVariableSave #Name = 'test', #Value=#MyVariable
print(' - Set #MyVariable = ' + CAST(#MyVariable AS VARCHAR(100)))
print(' - GO statement resets all variables')
GO -- This resets all variables including #MyVariable
declare #MyVariable int
exec dbo.MyVariableLoad 'test', #MyVariable output
print(' - Get #MyVariable = ' + CAST(#MyVariable AS VARCHAR(100)))
Output:
Test stored procedures for load/save of variables across GO statements:
- Set #MyVariable = 42
- GO statement resets all variables
- Get #MyVariable = 42
You can also use these:
exec dbo.MyVariableList -- Lists all variables in the temporary table.
exec dbo.MyVariableDeleteAll -- Deletes all variables in the temporary table.
Output of exec dbo.MyVariableList:
Name Value
test 42
It turns out that being able to list all of the variables in a table is actually quite useful. So even if you do not load a variable later, its great for debugging purposes to see everything in one place.
This uses a temporary table with a ## prefix, so it's just enough to survive a GO statement. It is intended to be used within a single script.
And the stored procedures:
-- Stored procedure to save a variable to a temp table.
CREATE OR ALTER PROCEDURE MyVariableSave
#Name varchar(255),
#Value varchar(MAX)
WITH EXECUTE AS CALLER
AS
BEGIN
SET NOCOUNT ON
IF NOT EXISTS (select TOP 1 * from tempdb.sys.objects where name = '##VariableLoadSave')
BEGIN
DROP TABLE IF EXISTS ##VariableLoadSave
CREATE TABLE ##VariableLoadSave
(
Name varchar(255),
Value varchar(MAX)
)
END
UPDATE ##VariableLoadSave SET Value=#Value WHERE Name=#Name
IF ##ROWCOUNT = 0
INSERT INTO ##VariableLoadSave SELECT #Name, #Value
END
GO
-- Stored procedure to load a variable from a temp table.
CREATE OR ALTER PROCEDURE MyVariableLoad
#Name varchar(255),
#Value varchar(MAX) OUT
WITH EXECUTE AS CALLER
AS
BEGIN
IF EXISTS (select TOP 1 * from tempdb.sys.objects where name = '##VariableLoadSave')
BEGIN
IF NOT EXISTS(SELECT TOP 1 * FROM ##VariableLoadSave WHERE Name=#Name)
BEGIN
declare #ErrorMessage1 as varchar(200) = 'Error: cannot find saved variable to load: ' + #Name
raiserror(#ErrorMessage1, 20, -1) with log
END
SELECT #Value=CAST(Value AS varchar(MAX)) FROM ##VariableLoadSave
WHERE Name=#Name
END
ELSE
BEGIN
declare #ErrorMessage2 as varchar(200) = 'Error: cannot find saved variable to load: ' + #Name
raiserror(#ErrorMessage2, 20, -1) with log
END
END
GO
-- Stored procedure to list all saved variables.
CREATE OR ALTER PROCEDURE MyVariableList
WITH EXECUTE AS CALLER
AS
BEGIN
IF EXISTS (select TOP 1 * from tempdb.sys.objects where name = '##VariableLoadSave')
BEGIN
SELECT * FROM ##VariableLoadSave
ORDER BY Name
END
END
GO
-- Stored procedure to delete all saved variables.
CREATE OR ALTER PROCEDURE MyVariableDeleteAll
WITH EXECUTE AS CALLER
AS
BEGIN
DROP TABLE IF EXISTS ##VariableLoadSave
CREATE TABLE ##VariableLoadSave
(
Name varchar(255),
Value varchar(MAX)
)
END
If you just need a binary yes/no (like if a column exists) then you can use SET NOEXEC ON to disable execution of statements. SET NOEXEC ON works across GO (across batches). But remember to turn EXEC back on with SET NOEXEC OFF at the end of the script.
IF COL_LENGTH('StuffTable', 'EnableGA') IS NOT NULL
SET NOEXEC ON -- script will not do anything when column already exists
ALTER TABLE dbo.StuffTable ADD EnableGA BIT NOT NULL CONSTRAINT DF_StuffTable_EnableGA DEFAULT(0)
ALTER TABLE dbo.StuffTable SET (LOCK_ESCALATION = TABLE)
GO
UPDATE dbo.StuffTable SET EnableGA = 1 WHERE StuffUrl IS NOT NULL
GO
SET NOEXEC OFF
This compiles statements but does not execute them. So you'll still get "compile errors" if you reference schema that doesn't exist. So it works to "turn off" the script 2nd run (what I'm doing), but does not work to turn off parts of the script on 1st run, because you'll still get compile errors if referencing columns or tables that don't exist yet.
You can make use of NOEXEC follow he steps below:
Create table
#temp_procedure_version(procedure_version varchar(5),pointer varchar(20))
insert procedure versions and pointer to the version into a temp table #temp_procedure_version
--example procedure_version pointer
insert into temp_procedure_version values(1.0,'first version')
insert into temp_procedure_version values(2.0,'final version')
then retrieve the procedure version, you can use where condition as in the following statement
Select #ProcedureVersion=ProcedureVersion from #temp_procedure_version where
pointer='first version'
IF (#ProcedureVersion='1.0')
BEGIN
SET NOEXEC OFF --code execution on
END
ELSE
BEGIN
SET NOEXEC ON --code execution off
END
--insert procedure version 1.0 here
Create procedure version 1.0 as.....
SET NOEXEC OFF -- execution is ON
Select #ProcedureVersion=ProcedureVersion from #temp_procedure_version where
pointer='final version'
IF (#ProcedureVersion='2.0')
BEGIN
SET NOEXEC OFF --code execution on
END
ELSE
BEGIN
SET NOEXEC ON --code execution off
END
Create procedure version 2.0 as.....
SET NOEXEC OFF -- execution is ON
--drop the temp table
Drop table #temp_procedure_version