Home / T-SQL / Script alle databases en objecten

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

 

Check Also

Book Review: Unlocking the Power of DAX: A Deep Dive into Marco Russo’s Definitive Guide

The Definitive Guide to DAX: Business intelligence for Microsoft Power BI, SQL Server Analysis Services, …

Geef een reactie

Het e-mailadres wordt niet gepubliceerd. Vereiste velden zijn gemarkeerd met *