SQLBlog Nederland

Script alle databases en objecten

In navolging op een voorgaand artikel over het scripten van je databaseobjecten heb ik een stored procedure gemaakt die automatisch alle databases voor je scripts en het script wegschrijft naar een folder. Dit script is gemaakt in SQL Server 2005. Dit is handig omdat je nu alle objecten zoals tabellen, stored procedures, views en functies in een script hebt.

CREATE PROCEDURE [dbo].[sp_GenDBscript] @vcDatabase as Varchar(50)
AS
/*
Getest 27-7-2011 met de volgende settings
C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Publishing\1.2>sqlpubwiz
e script -schemaonly -d DWH_NL_REF -S MSINTFR07666\BENL_DWH_1 c:\script.sql

Example:
EXEC dbo.[sp_GenDBscript] 'DWH_NL_REF'
*/

DECLARE @vcPath as Varchar(150)
DECLARE @vcCMD as Varchar(150)
DECLARE @vcParam as Varchar(150)
DECLARE @vcTotcmd as Varchar(250)
DECLARE @vcDate as Varchar(10)
DECLARE @vcServer as Varchar(150)
DECLARE @vcTextPath as Varchar(150)
DECLARE @vcTextFile as Varchar(150)
DECLARE @vcMkdirStr as Varchar(150)
DECLARE @vcTime as Varchar(150)
DECLARE @iRC as Int

Set @vcTime = REPLACE(Convert(varchar,getdate(), 114),':','')
SET @vcDate = Convert(varchar, getdate(), 112)
SET @vcTextPath = 'F:\DWH_NL\SCRIPTS\' + @vcDatabase
SET @vcTextFile = @vcDatabase + '_' + @vcDate + '_' + @vcTime + '.sql'
SET @vcMkdirStr = 'mkdir ' + @vcTextPath
SET @vcServer = @@SERVERNAME

--checking if dir exist, If it doesnt exist it creates it
EXEC @iRC = master.dbo.xp_cmdshell @vcMkdirStr, NO_OUTPUT
IF @iRC <> 0
BEGIN
 exec master.dbo.xp_cmdshell @vcMkdirStr , NO_OUTPUT
END 

SET @vcPath = '"C:\Program Files (x86)\Microsoft SQL Server\90\Tools\Publishing\1.2\SqlPubWiz.exe"'
SET @vcParam = ' script ' + @vcTextPath + '\' + @vcTextFile + ' -S ' + @vcServer + ' -schemaonly -d ' + @vcDatabase
SET @vcTotcmd = @vcPath + @vcParam

print @vcTotcmd

EXEC master..xp_cmdshell @vcTotcmd

 

Mobiele versie afsluiten