Create database from a template by a script - sql-server

I'm running a robot test on one of our test environments, and every night, before the test runs, I would like to dump the database, and create it again from a template.
I know that PSQL has a solution for it:
CREATE DATABASE name
[ TEMPLATE [=] template ]
Is there a way I can do this in SQL Server, and write a script for it?

You can write any kind of functionality as text and then execute it as a variable. That way you can store your template as text, where you would define the database.
declare #example nvarchar(max)
set #example = 'create database examplebase'
exec sp_executesql #example
You can use this in a stored procedure where you can set database name ect. as a parameter.
create PROCEDURE sp_recreateDB
-- Add the parameters for the stored procedure here
#databasename nvarchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
declare #example nvarchar(max)
SET #example = N'CREATE DATABASE ' + QUOTENAME(#Databasename) + N';'
-- ect...
exec sp_executesql #example
END
GO

Related

SQL Select table name

A database had has 4 tables that has the same columns EG. SalesJAn, SalesFeb, SalesMarch, SalesApril.
I want to run a query in SQL server or in report builder Where i can change the table name based on a selection which one of 4 tables will be queried . Eg Filter in report builder
Like this
declare #tablename varchar(50)
set #tablename = 'test'
select * from #tablename
You can create a procedure which will do a select for a given table name. This procedure could look like this:
CREATE PROCEDURE EXECUTE_SELECT
#tbl sysname
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQL NVARCHAR(MAX);
SET #SQL = N' SELECT * FROM ' + QUOTENAME(#tbl)
EXECUTE sp_executesql #SQL
END
Then you can execute this procedure for every table name you want. Please see here an example according to your description: db<>fiddle
If this doesn't help you, please point out which exactly you still need to know. Thank you.

Stored procedure to alter database recovery mode isnt compiling

I am trying to create a stored procedure that would be generic. I am trying to alter a database and set the recovery mode to either simple or full. It would accept database name and mode as parameter.
The SQL query executes in the context of the master database and alters the database specified. I am trying to incorporate it via Execute SQL task in SSIS. I need the stored procedure to reside in the database that is going to perform the operation on. Not sure how that is going to work. USE database keyword is not allowed in the stored procedure...
The original query works fine but I am facing an issue while trying to execute the stored procedure in the database.It says 'RECOVERY' is not a recognized SET option.
Original query:
use master
ALTER DATABASE XYZ
SET RECOVERY FULL
Stored procedure:
USE XYZ
GO
CREATE PROCEDURE DatabaseRecoveryMode
(#mode varchar(10),
#database varchar(50))
AS
BEGIN
ALTER DATABASE #database
SET RECOVERY #mode
END
The ALTER DATABASE documentation shows the recovery model is a keyword, not a variable. You'll need to construct and execute a dynamic SQL statement for this.
CREATE PROCEDURE dbo.DatabaseRecoveryMode
(
#mode nvarchar(11),
#database sysname
)
AS
IF #mode NOT IN(N'SIMPLE', N'BULK_LOGGED', N'FULL')
BEGIN
RAISERROR('Recovery model must be SIMPLE, BULK_LOGGED, OR FULL', 16, 1);
RETURN 1;
END;
DECLARE #SQL nvarchar(MAX) = N'ALTER DATABASE '
+ QUOTENAME(#database)
+ N' SET RECOVERY '+ #mode + N';';
EXECUTE(#SQL);
GO
You need to use dynamic SQL
USE XYZ
GO
Create Procedure DatabaseRecoveryMode
(
#mode varchar(10),
#database varchar(50)
)
AS
begin
DECLARE #SQL NVARCHAR(MAX)
DECLARE #db NVARCHAR(60), #Use NVARCHAR(100)
SET #db = N'master'
SET #Use = N'Use ' + #db
SET #SQL = #Use + N' ALTER DATABASE '+ #database + N' SET RECOVERY ' + #mode ;
--SELECT #SQL
EXEC sys.sp_executesql #SQL ;
end
GO

T-SQL : how to use exec to insert into table not previously created?

I have the following code:
Declare #strSQL varchar(max);
set #strSQL = N'REALLY LONG QUERY';
exec (#strSQL) at <LinkedServerName>;
I did this because the query is longer than 8000 characters (it cannot be changed, it just has too many columns). It works, but I need to insert it into a temporal table that does not yet exist. So, I do not want to run the create table before hand. So, where should I write INTO tmp_table for correct syntax?
For example, this does not work:
exec (#strSQL) INTO tmp_table at <LinkedServerName>;
Declare #strSQL varchar(max);
if object_id('tempdb..MyTempTable') is not null drop table tempdb.dbo.MyTempTable
set #strSQL = N'select * into tempdb.dbo.MyTempTable from (REALLY LONG QUERY) k';
exec (#strSQL) at <LinkedServerName>;
-- for check of existence of table for linkedserver add it into #strSQL
or
replace tempdb.dbo.MyTempTable with temp table ##Table (for local server)
or
decompose and normalize your model, if you have qry with thousands chars you don't need dynamical qry but rethink your solution - for example use views or pivot your output

SQL Server / Create view from stored procedure

I am trying to create a view out of a stored procedure and am perplexed to see two opposing results from a very similar approach.
Example 1
CREATE PROCEDURE cv AS
GO
DECLARE #sql nvarchar(MAX)
SET #sql = 'CREATE VIEW test AS SELECT * FROM someOtherTable'
exec (#sql)
Whereas this example creates the view once the procedure is created for the 1st time, it will not recreate the view when I execute the procedure at a later stage using:
EXEC cv
Example 2
CREATE PROCEDURE cv
#table SYSNAME
AS
DECLARE #sql nvarchar(MAX)
SET #sql = 'CREATE VIEW '+ #table +' AS SELECT * FROM someOtherTable'
This one instead does not create the view when the procedure is created for the first time but creates the view afterwards every time it is called by:
EXEC #sql;
Why is this the case? I think this is really confusing and does not make sense or does it?
For your 1st statement
CREATE PROCEDURE cv AS
GO --<-- This GO here terminates the batch
DECLARE #sql nvarchar(MAX)
SET #sql = 'CREATE VIEW test AS SELECT * FROM someOtherTable'
exec (#sql)
the GO batch terminator create the procedure and the EXECUTES the following statement straightaway. So it appears to you as you have created a procedure which created the view for you.
Infact these are two statements in two batches.
--BATCH 1
CREATE PROCEDURE cv AS
GO
--BATCH 2
DECLARE #sql nvarchar(MAX)
SET #sql = 'CREATE VIEW test AS SELECT * FROM someOtherTable'
exec (#sql)
Batch 1 Creates a procedure which has nothing inside it, but it creates a procedure object for you with no functionality/Definition at all.
Statement after the key word GO is executed separately and creates the view for you.
My Suggestion
Always check for an object's existence before you create it. I would write the procedure something like this..
CREATE PROCEDURE cv
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID ('test', 'V') IS NOT NULL
BEGIN
DROP VIEW test
END
DECLARE #sql nvarchar(MAX)
SET #sql = 'CREATE VIEW test AS SELECT * FROM someOtherTable'
exec (#sql)
END
In Example 1 - you are creating a view with a hard-coded name of test. On subsequent runs of your proc, as the view already exists, SQL Server will throw an error because you are trying to create a view with the same name as one that already exists.
In Example 2, you are passing in the name of the view as a parameter. This will always create a new view unless the #table value you pass in corresponds to an existing view.
Just wondering - why are you creating a view with a stored proc? This is not something you would normally do in SQL.
You need to change
EXEC #sql to EXEC (sql)
EXEC can be use to run stored procedure, not dynamic sql
eg.
declare #dd varchar(100)='Select ''A'''
exec (#dd) ->will work fine
exec #dd -> Error
Read more about The Curse and Blessings of Dynamic SQL
Create view statement cannot be used with a stored procedure
EXEC ('CREATE VIEW ViewName AS SELECT * FROM OPENQUERY(Yourservername,''EXECUTE [databasename].[dbo].[sp_name] ''''' +Parameter + ''''''')')

Dynamic parameters for sql query with "IN" operator

I have an ASP.NET website (c#) and in the code-behind I want to use the IN operator in SQL http://www.w3schools.com/sql/sql_in.asp to get data from my database.
The syntax is:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
I use a stored procedure to get data, inside this procedure I run, in the end, the select.
My question is how to build dynamically the (value1, value2, ...) part of the query? How do I send as SqlParameter(s) the values that appear in the IN operator?
The stored procedure is defined like this:
CREATE PROCEDURE [dbo].[GetAllUsers]
#ORGANIZATION_ID int = null
AS
BEGIN
SET NOCOUNT ON;
begin
SELECT *
from USERS
where ORGANIZATION_ID = #ORGANIZATION_ID
end
END
I'd like to replace the WHERE clause with something like:
WHERE ORGANIZATION in (xxxxxxxxxxxxx)
How to do this?
Thank you.
You can use dynamic sql:
CREATE PROCEDURE [dbo].[GetAllUsers]
#ORGANIZATION_ID varchar(max) = null
AS
BEGIN
declare #sql varchar(max)
#sql = 'SELECT *
from USERS
where ORGANIZATION_ID in ('+#ORGANIZATION_ID+')'
SET NOCOUNT ON;
begin
exec(#sql)
end
END
You have to change type of #ORGANIZATION_ID to varchar and run the procedure with
one id:
exec '1'
or list of ids:
exec '1,2,3,4'

Resources