Make copies of database - sql-server-2008-r2

I have a database with all tables needed, on which is perfectly usable. But for test purposes, I need to make copies of the database for, lets say 100 times. (My application will loop on each database to execute some scripts).
The databases generated should bear different names of course. To use Backup/Restore or even Detach/Copy/Attach a 100 times is not do-able. So I would like to know if there's a script which can loop to copy/restore a database several times on different names?
Thanks

Ok found something that's working for me, by simple WHILE LOOP;
DECLARE #index int
DECLARE #dbName varchar(25)
declare #HRNET varchar(200)
declare #HRNET_LOG varchar(200)
declare #sql varchar(2000)
SET #index = 5
WHILE (#index < 200)
BEGIN
-- Construct db name and corresponding files name
SET #dbName = 'BDName' + Right('0000' + CONVERT(NVARCHAR, #index), 4)
set #MDF = '''C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQL2008\MSSQL\DATA\' + #dbName + '.mdf'''
SET #LDF = '''C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQL2008\MSSQL\DATA\' + #dbName + '_1.ldf'''
-- Restore db from backup bak file
SELECT #sql = 'RESTORE DATABASE ' + #dbName + '
FROM DISK = ''C:\DB Backup\DBName1919.bak''
WITH FILE = 1,
MOVE ''WEEKLY_UK_CO_E_REPORTING_Data'' TO ' + #MDF + ',
MOVE ''WEEKLY_UK_CO_E_REPORTING_Log'' TO ' + #LDF +
', NOUNLOAD, STATS = 10'
exec(#sql)
SET #index = #index + 1
END
GO
To retrieve the backup path location (MDF & LDF), just run the following;
RESTORE FILELISTONLY
FROM DISK = N'C:\DB Backup\DBName1919.bak'

Related

getting different file size when reading pdf from disc to varbinary(max) column and subsequently bcp-ing it back to disc

So in setting the test environment for SQL Agent job I'm working on I populated a varbinary(max) field from a pdf file on disc using OPENROWSET like so
DECLARE #File varbinary(max)
SELECT #File=BulkColumn
FROM OPENROWSET
(BULK 'v:\DIMA.pdf', SINGLE_BLOB) pdf
UPDATe Invoice_FileList SET Fajl=#File WHERE ID=4
Afterwards I write the file back to disc like so
DECLARE #bcpCommand nvarchar(1000), #ID bigint, #UID bigint
DECLARE #FileName nvarchar(256), #FileDir nvarchar(128) = 'v:\'
SELECT #ID=ID, #UID=UID, #FileName =#FileDir + ImeFajla FROM ABImport_ImmoF.dbo.Invoice_FileList WHERE ID=4
SET #bcpCommand = 'bcp "SELECT Fajl FROM ABImport_ImmoF.dbo.Invoice_FileList WHERE ID = ' + CAST(#ID AS VARCHAR(20)) + ' AND UID = ' + CAST(#UID AS VARCHAR(20)) + '" queryout "' + #FileName + '" -T -N -S ' + ##SERVERNAME
print #bcpCommand
EXEC master..xp_cmdshell #bcpCommand
Everything seemingly works fine, but the original pdf file and the file bcp saves to disk differ in size by few bytes and while looking identical when opened in pdf reader, comparing their respective hex shows that they are very much different.
Can someone explain to me why is that so (and since they are looking the same when opened in pdf reader do I need to worry about it at all)

Restore multiple transaction log backup from disk

We are receiving transaction log backups from a vendor for a off-site database. We have already restored the full backup in Standby mode. we will be receiving multiple transaction log backups everyday. I need a script to restore the transaction log backups to standby mode. The script I am trying to use pulls the files into the filelist, but the script is not doing anything and I can't figure out why.
Can someone help me figure this out?
USE Master;
GO
SET NOCOUNT ON
-- 1 - Variable declaration
DECLARE #dbName sysname
DECLARE #backupPath NVARCHAR(500)
DECLARE #cmd NVARCHAR(500)
DECLARE #fileList TABLE (backupFile NVARCHAR(255))
DECLARE #lastFullBackup NVARCHAR(500)
DECLARE #lastDiffBackup NVARCHAR(500)
DECLARE #backupFile NVARCHAR(500)
-- 2 - Initialize variables
SET #dbName = 'Telcor'
SET #backupPath = 'D:\TelcorLogDump\'
-- 3 - get list of files
SET #cmd = 'DIR /b "' + #backupPath + '"'
INSERT INTO #fileList(backupFile)
EXEC master.sys.xp_cmdshell #cmd
DECLARE backupFiles CURSOR FOR
SELECT backupFile
FROM #fileList
WHERE backupFile LIKE '%.TRN'
AND backupFile LIKE #dbName + '%'
-- AND backupFile > #lastFullBackup
OPEN backupFiles
-- Loop through all the files for the database
FETCH NEXT FROM backupFiles INTO #backupFile
WHILE ##FETCH_STATUS = 0
BEGIN
SET #cmd = 'RESTORE LOG [' + #dbName + '] FROM DISK = '''
+ #backupPath + #backupFile + ''' WITH STANDBY = N''D:\TelcorLogDump\ROLLBACK_UNDO_Telcor.BAK'
PRINT #cmd
FETCH NEXT FROM backupFiles INTO #backupFile
END
CLOSE backupFiles
DEALLOCATE backupFiles
I had to add two extra ticks at the end:
ROM DISK = '''
* #backupPath + #backupFile + ''' WITH STANDBY = N''D:\TelcorLogDump\ROLLBACK_UNDO_Telcor.BAK
'''

How to import multiple CSV files into SQL Server tables?

I am using SQL Server 2017 version, and I want to import multiple .csv files into multiple tables in SQL server.
I found the following script in the net,
--BULK INSERT MULTIPLE FILES From a Folder
--a table to loop thru filenames drop table ALLFILENAMES
CREATE TABLE ALLFILENAMES(WHICHPATH VARCHAR(255),WHICHFILE varchar(255))
--some variables
declare #filename varchar(255),
#path varchar(255),
#sql varchar(8000),
#cmd varchar(1000)
--get the list of files to process:
SET #path = 'C:\Dump\'
SET #cmd = 'dir ' + #path + '*.csv /b'
INSERT INTO ALLFILENAMES(WHICHFILE)
EXEC Master..xp_cmdShell #cmd
UPDATE ALLFILENAMES SET WHICHPATH = #path where WHICHPATH is null
--cursor loop
declare c1 cursor for SELECT WHICHPATH,WHICHFILE FROM ALLFILENAMES where WHICHFILE like '%.csv%'
open c1
fetch next from c1 into #path,#filename
While ##fetch_status <> -1
begin
--bulk insert won't take a variable name, so make a sql and execute it instead:
set #sql = 'BULK INSERT Temp FROM ''' + #path + #filename + ''' '
+ ' WITH (
FIELDTERMINATOR = '','',
ROWTERMINATOR = ''\n'',
FIRSTROW = 2
) '
print #sql
exec (#sql)
fetch next from c1 into #path,#filename
end
close c1
deallocate c1
But the problem is I cannot use the command 'EXEC Master..xp_cmdShell' cause it was disabled by DBA's due to some security reasons, and they are not permitting me to use it. Is there any alternative command that I can use instead of 'xp_cmdShell' in the same script.
In this script near bulk insert command (set #sql = 'BULK INSERT Temp FROM ''' + #path + #filename + ''' '
+ ') I see only one table name 'Test', and how can I mention multiple table names in the Bulk insert command?
Any help please.
It's been a long time since I have had to do this, but this is how I used to do these kinds of things.
DECLARE #intFlag INT
SET #intFlag = 1
WHILE (#intFlag <=100)
BEGIN
PRINT #intFlag
declare #fullpath1 varchar(1000)
select #fullpath1 = '''\\FTP\' + convert(varchar, getdate()- #intFlag , 112) + '_your_file.csv'''
declare #cmd1 nvarchar(1000)
select #cmd1 = 'bulk insert [dbo].[your_table] from ' + #fullpath1 + ' with (FIELDTERMINATOR = ''\t'', FIRSTROW = 5, ROWTERMINATOR=''0x0a'')'
exec (#cmd1)
SET #intFlag = #intFlag + 1
END
GO
As you can tell, this is looping through a bunch of files with dates as file names. The first part of each file name was in this date format: convert(varchar, getdate()- #intFlag , 112)
I'm guessing your files have names that match some specific pattern.
SQl Server has a tool that does this for you. Goto to your SQL Server folder
Open SQL Server Import and Export Wizard.
Choose a Data Source Microsoft Excel
Select the Excel File. And following the steps

Creating and inserting into a DB using Dynamic SQL

To whoever reads this,
Basically using dynamic SQL, i am trying to create a database and then insert into it. Problem is that I cant find an alternative to 'GO' since when i run it i get an error saying the newly created DB doesn't exist. I know that it cant be used in dynamic sql as it is not recognized as T-SQL. I've also tried adding ";" but error still persists.
DECLARE #TargetDB sysname
DECLARE #TargetSchema sysname
DECLARE #TargetTable sysname
DECLARE #SourceDB sysname
DECLARE #SourceSchema sysname
DECLARE #SourceTable sysname
DECLARE #sql NVARCHAR(max)
SET #SourceDB = 'AYOOO'
SET #TargetDB = #SourceDB + 'SandBox'
SET #SourceTable = 'GUCCI'
SET #TargetTable = #SourceTable + 'SandBox'
SET #sql = N'CREATE DATABASE ' + #TargetDB + '; ' --create new db
SET #sql = #sql + N' SELECT * INTO ' + #TargetDB +'.dbo.'+#TargetTable+' FROM ' + #SourceDB+'.dbo.'+#SourceTable; --these 2 lines are for copying data into new tables
PRINT #sql
EXEC sys.sp_executesql #sql
Error:
Database 'AYOOOSandBox' does not exist.
I know its a stupid question but I'd like to find a good alternative to "GO" or a better practice for Dynamic SQL.
Thanks
After fixing your SQL to not be a huge injection issue, by properly quoting your objects, you need to separate the statements into 2 commands. Then you can CREATE your database in one command, and then INSERT in another.
DECLARE #TargetDB sysname,
#TargetSchema sysname,
#TargetTable sysname,
#SourceDB sysname,
#SourceSchema sysname,
#SourceTable sysname,
#sql nvarchar(MAX),
#CRLF nchar(2) = NCHAR(13) + NCHAR(10);
SET #SourceDB = 'AYOOO';
SET #TargetDB = #SourceDB + 'SandBox';
SET #SourceTable = 'GUCCI';
SET #TargetTable = #SourceTable + 'SandBox';
SET #sql = N'CREATE DATABASE ' + QUOTENAME(#TargetDB) + N';'; --create new db
EXEC sys.sp_executesql #sql;
SET #sql = N'SELECT *' + #CRLF +
N'INTO ' + QUOTENAME(#TargetDB) + N'.dbo.' + QUOTENAME(#TargetTable) + #CRLF +
N'FROM ' + QUOTENAME(#SourceDB) + N'.dbo.' + QUOTENAME(#SourceTable) + N';'; --copying data into new tables
EXEC sys.sp_executesql #sql;

Create View in T-SQL Script

We are running SQL Server 2008 R2 and creating an archiving function that will create a new database (that can later be taken offline and stored elsewhere), then take data out of our primary database and put it in to the new DB and finally, create a view in the primary DB to look at the archived data in the new table.
I have the script to create the DB, create the archive table in the new DB, copy the records from the primary DB and put them in to the archive DB and delete the records from the primary DB. Now I am trying to script the creation of a view:
declare #sql varchar(8000)
set #sql = 'create view [' + #srcdb + '].[dbo].[vw_artrans] as
select * from [' + #srcdb + '].[dbo].artrans
union
select * from [' + #archdb + '].[dbo].artrans'
exec (#sql)
But you cannot pass the name of the DB to create view.
So I tried this instead:
declare #sql varchar(8000)
set #sql = 'use ' + #srcdb + '
go
create view [vw_artrans] as
select * from [' + #srcdb + '].[dbo].artrans
union
select * from [' + #archdb + '].[dbo].artrans'
exec (#sql)
But it now complains about the GO statement (Incorrect syntax).
The name of the database being created for the archived data is determined dynamically in the script (#archdb contains the name) so I can't script in the DB name and I can't run a second script.
Based on #Sebastien answer, here is the solution :
declare #sql varchar(8000)
set #sql = 'EXEC ' + #srcdb + '.sys.sp_executesql N''create view [vw_artrans] as
select * from [' + #srcdb + '].[dbo].artrans
union
select * from [' + #archdb + '].[dbo].artrans'';'
exec (#sql)
to execute a dynamic SQL statement in a different database than the one you are in you can use sp_executesql like this:
USE db1;
EXEC db2.sys.sp_executesql N'SELECT DB_NAME();';
This wil result in db2 being returned.
GO is not a T-SQL statement. It is interpreted by SSMS to break the query text into batches. It never gets send to SQL Server itself.