Quantcast
Channel: Welcome To TechBrothersIT
Viewing all 1927 articles
Browse latest View live

How to Change Recovery Model from Simple to Full for Multiple Databases in SQL Server - SQL Server Tutorial

$
0
0

Scenario:

You are working as SQL Server DBA or Developer and you need to prepare the script that should change the recovery model of databases which are in Simple to Full.

The below script can be used to change the recovery model from simple to full, You can change the select query to include or exclude database for which you want to change recovery model from simple to full.


USE MASTER
GO
DECLARE @DBName VARCHAR(200)
DECLARE DB_Cursor CURSORFOR
--Select the database for which you want to change
--Recovery model from Simple to Full
SELECT name
FROM sys.databases
WHERE name NOTIN ( 'master', 'tempdb', 'model', 'msdb' )
and recovery_model_desc='Simple'
OPEN DB_Cursor
FETCHNEXTFROM DB_Cursor INTO @DBName
WHILE@@FETCH_STATUS = 0
BEGIN

DECLARE @SQL NVARCHAR(500)=Null

SET @SQL='ALTER DATABASE [' + @DBName
+ '] SET RECOVERY FULL'

PRINT @SQL

EXEC ( @SQL)

FETCHNEXTFROM DB_Cursor INTO @DBName
END

CLOSE DB_Cursor
DEALLOCATE DB_Cursor

--Check if Recovery Model is changed to Full
SELECT name, recovery_model_desc
FROM sys.databases

I executed  the above script and it was able to change recovery model for database from simple to full.

How to change recovery model of databases from simple to full in SQL Server


How to take Transaction Log Backups for All SQL Server Databases in SQL Server - SQL Server Tutorial

$
0
0

Scenario:

You are working as DBA or developer and you have to prepare the scripts that should be able to take the transaction log backup for all the databases. You can use these script on ad hoc basis if you need or you can use it SQL Server agent job on schedule. 

The list of databases can be change as per requirement. You can change Select statement and filter for the database you want or don't want to contribute in Transaction Log backup.

I am excluding system databases as you can see that I have database_id > 4 in where clause. The script will take transaction log backup for all the database which are in full or bulk recovery mode.

USE MASTER
GO
DECLARE @BackupPath varchar(100)
--Provide the backup path
SET @BackupPath = 'C:\Backup\'
DECLARE @DatabaseName ASvarchar(128)

DECLARE Cur CURSORFOR
--Change the select query for the DBs you like to backup
SELECT
name
FROM sys.databases
WHERE database_id>4
and recovery_model_desc in ('Full','BULK_LOGGED')

OPEN Cur
FETCHNEXTFROM Cur INTO @DatabaseName
WHILE@@FETCH_STATUS = 0
BEGIN
DECLARE @SQLvarchar(max) = NULL
DECLARE @DBNamewithDateTime varchar(128) = NULL
SET @DBNamewithDateTime = @DatabaseName + '_' + REPLACE(CAST(GETDATE()
ASdate), '-', '') + '_' + REPLACE(CAST(CAST(GETDATE() AStime)
ASchar(8)), ':', '')

SET @SQL = 'BACKUP LOG [' + @DatabaseName + '] TO DISK = N''' +
@BackupPath + '' + @DBNamewithDateTime + '.trn''
WITH NOFORMAT, NOINIT, NAME = N'
'' + @DBNamewithDateTime
+ '-Tran Log Backup'',
SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10'


PRINT @SQL
EXEC (@SQL)
FETCHNEXTFROM Cur INTO @DatabaseName
END
CLOSE Cur
DEALLOCATE Cur


I executed above script and it took transaction log backup with date-time as shown below.
How to take transaction log backup of all databases on SQL Server Instance - SQL Server Tutorial

How to save resultset of RESTORE FILELISTONLY in temp table in SQL Server - SQL Server Tutorial

$
0
0

Scenario:

I got this task to read the backup files form a folder then then restore to new location. While was working on this task, needed to read the file names from .bak file. I need to move them to new location.

I can use RESTORE FILELISTONLY to get the information. As I need to save the information into variables and build restore query, I had to read this into a temp table.

Below query can be used to save the result set of RESTORE FILELISTONLY to temp table.


--Drop temp table if exits
IF OBJECT_ID('tempdb..#BackupFiles') ISNOTNULL
DROPTABLE #BackupFiles


Declare @BackupFilePath VARCHAR(500)
SET @BackupFilePath='c:\Backup\ReportServer1_20160413_111603.bak'

--Create Temp Table
Createtable #BackupFiles(
LogicalName VARCHAR(128),
PhysicalName VARCHAR(MAX),
Type CHAR(10),
FileGroupName VARCHAR(100),
Size BigInt,
MaxSize BigInt,
Field Int,
CreateLSN INT,
DropLSN INT,
UniqueId uniqueidentifier,
ReadonlyLSN Int,
ReadWriteLSN Int,
BackupSizeInBytes BigInt,
SourceBlockSize Int,
FileGroupIt bit,
LogGroupGUID uniqueidentifier,
DifferentialBaseLSN Bigint,
DifferentialBaseGUID uniqueidentifier,
IsReadOnly bit,
IsPresent bit,
TDEThumprint uniqueidentifier)

--Insert data from RESTORE FILELISTONLY
insertinto #BackupFiles ([LogicalName]
,[PhysicalName]
,[Type]
,[FileGroupName]
,[Size]
,[MaxSize]
,[Field]
,[CreateLSN]
,[DropLSN]
,[UniqueId]
,[ReadonlyLSN]
,[ReadWriteLSN]
,[BackupSizeInBytes]
,[SourceBlockSize]
,[FileGroupIt]
,[LogGroupGUID]
,[DifferentialBaseLSN]
,[DifferentialBaseGUID]
,[IsReadOnly]
,[IsPresent]
,[TDEThumprint])
EXEC('RESTORE FILELISTONLY FROM DISK = '''+@BackupFilePath+'''')


--Check the temp table if data is inserted
Select * From #BackupFiles


I executed above query on different backup files and works great to get me the result set into temp table from RESTORE FILELISTONLY.

How to Insert SQL Server RESTORE FILELISTONLY Result set into Temp table - SQL Server Tutorial

C# - How to get file Properties and insert into SQL Server table by using CSharp

$
0
0

Scenario: Download Script

You are working as C# developer, you need to write a program that can read file's information such as

  •   FolderPath
  •   FileName
  •   LastWriteTime
  •   CreateTime
  •   FileSizeinKB


from a table and write into SQL Server table. Also as part of file information , you would like to insert folder from which we are reading the file properties.


Step 1: 
First of all you need to create a table in SQL Server database in which you would like to insert file information.

CREATETABLE [dbo].[FileInformation](
id intidentity(1,1),
FolderPath VARCHAR(255),
FileName VARCHAR(255),
[LastWriteTime] DateTime,
[CreateTime] Datetime,
FileSizeinKB Int)

Step 2:
Create new Project and then choose Console Application and use below script.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SqlClient;

namespace _01_WriteFileProperitestoTable
{
class Program
{
staticvoid Main(string[] args)
{
//Declare Variable and set value,Provide the folder which contains files
string VarDirectoryPath = "C:\\Source\\";
//Create Connection to SQL Server
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString= "
Data Source = (local); Initial Catalog =TechBrothersIT; "
               + "Integrated Security=true;";

//get all files from directory or folder to get file's information
string[] files = Directory.GetFiles(VarDirectoryPath);
SqlCommand SqlCmd = new SqlCommand();
SqlCmd.Connection = SQLConnection;
SQLConnection.Open();

//loop through files
foreach (string filename in files)
{

FileInfo file = new FileInfo(filename);

SqlCmd.CommandText = "
Insert into dbo.FileInformation(";
SqlCmd.CommandText += "
[FolderPath],[FileName],[LastWriteTime],[CreateTime],[FileSizeinKB])";
SqlCmd.CommandText +="
Values('"
+ VarDirectoryPath + "'
,'"
+ file.Name + "'
,'"
+ file.LastWriteTime + "'
,'"
+ file.CreationTime
+ "'
,'" + file.Length / 1024
+ "'
)";
SqlCmd.ExecuteNonQuery();
}
SQLConnection.Close();
}
}
}

Save the script and then execute. It should read the file properties from the folder you have given and insert into SQL Server Table.
How to read file's properties in C# and insert into SQL Server Table - C# Tutorial


C# - Delete files from a folder those are older than some number of days by using CSharp

$
0
0

Scenario: Download Script

You are working as C# developer and you need to write a program that should delete the files from a folder older than some number of days.


Solution:

You can write Console Application for this purpose.  Below is the script that can be used to delete older files, You can change folder path according to your folder path and number of days you like to pass for old files. I only added System.IO namespace.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _02_DeleteOldFilesFromFolder
{
class Program
{
staticvoid Main(string[] args)
{
//Declare Variables and Set Values
string FileDirectory;
int RetentionPeriodinDays;

FileDirectory =
"C:\\Source\\";
RetentionPeriodinDays = 2;

var files = new DirectoryInfo(FileDirectory).GetFiles("
*.*");
foreach (var file in files)
{

if (file.CreationTime < DateTime.Today.AddDays(-RetentionPeriodinDays))
{
file.Delete();
}
}

}
}
}

C# - How to get Oldest file from a folder by using CSharp

$
0
0

Scenario: Download Script

You are working as C# developer and you need to write code to find oldest file from a folder. There could be different reasons for this requirement such as


  • You would like to delete the oldest file from a folder and load the new files
  • You would like to load the oldest file, once you found it


Solution:
I create a Console Application and saved the oldest file name in variable, from there you can use this variable according to your requirement.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _03_Get_The_oldest_files_from_folder
{
class Program
{
staticvoid Main(string[] args)
{

//Provide folder path from which you like to get oldest file
string Folder = "C:\\Source\\";
var files = new DirectoryInfo(Folder).GetFiles("
*.*");
string OldestFile = "
";

DateTime lastModified = DateTime.MaxValue;

foreach (FileInfo file in files)
{
if (file.LastWriteTime < lastModified)
{
lastModified = file.LastWriteTime;
OldestFile = file.Name;
}
}
//To see the value of OldestFile variable, You can remove both lines
Console.WriteLine(OldestFile);
Console.ReadLine();
}
}
}

C# - Why console window disappear immediately without display my output in C Sharp?

$
0
0

Scenario: Download Scripts

You are working as C# developer and writing Console Application. You would like to display some statics string values and also variables values but console window disappear immediately without you can take a look.

As the values are displayed, so programs completes without waiting for you. One solution for this is to use Console.ReadLine() so it will wait from you to provide input. Once you are done seeing the value, you can simply hit Enter to close the window.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04_Console_Screen_Disappear_Immediately
{
class Program
{
staticvoid Main(string[] args)
{
string testvariable = "This is string variable";
//Display string
Console.WriteLine("Welcome to TechBrothersIT.com");
//display variable variable
Console.Write(testvariable);
//wait for input
Console.ReadLine();
}
}
}


I executed above script and it displayed the values and waited for me to hit Enter to close the console window as we have used the Console.ReadLine().
Console window closing immediately without displaying my output - C#

C# - What is the difference between Console.Write and Console.WriteLine Methods in C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer and writing Console Application. You need to display some lines and variables values to Console.

You can use Console.Write( ) or Console.WriteLine() functions.

Console.Write() method will write the values to the screen without adding new line character, that means if you try to print anything, it will start from the same line.

Console.WriteLine() method will write the values to screen also also include new line character. That means if you write another after that it will start from next line.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04_Console_Screen_Disappear_Immediately
{
class Program
{
staticvoid Main(string[] args)
{
string testvariable = "This is string variable";
//Display string
Console.Write("This is first Line ");
Console.WriteLine("2nd Line Welcome to TechBrothersIT.com");
//display variable variable
Console.Write(testvariable);
//wait for input
Console.ReadLine();
}
}
}

Diffrence between Write and WriteLine Methods in C#


C# - How to get the latest file from a folder by using C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer and you need to get the latest file from a folder. There could be different reasons you want to get the latest file, You might get the files in a folder and you need to get the get the latest to load to SQL server Table.

Below sample script can be used to get the latest file from folder. I have saved the latest file name in variable and printed on screen by using Console.Write() method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//Provide folder path from which you like to get latest file
string Folder = @"C:\Source\";
var files = new DirectoryInfo(Folder).GetFiles("
*.*");
string latestfile = "
";

DateTime lastModified = DateTime.MinValue;

foreach (FileInfo file in files)
{
if (file.LastWriteTime > lastModified)
{
lastModified = file.LastWriteTime;
latestfile = file.Name;
}
}
//To see the value of latest variable, You can remove both lines
Console.Write("
Latest File Name: "+latestfile);
Console.ReadLine();
}
}
}
How to find the most recent file in a directory by using C#



C# - How to copy all files in a folder to another folder in C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer and you need to create a Console Application, that should read all the files from a folder and copy to another folder in C#.

The below script can be used to copy all the files from a folder to new folder in C Sharp.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//Provider Source Folder Path
string SourceFolder = @"C:\Source\";
//Provide Destination Folder path
string DestinationFolder = @"
C:\Destination\";

var files = new DirectoryInfo(SourceFolder).GetFiles("
*.*");

//Loop throught files and copy to destination folder
foreach (FileInfo file in files)
{
file.CopyTo(DestinationFolder + file.Name);
}

}
}
}

C# - How to copy files and overwriting existing files if exists in a folder by using C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer and you need to write a program that should copy all the files from a folder to another folder, In case files already exists, you want to overwrite with new file from source folder.

Below script can be used to copy all the files from a folder to another folder and overwrite if exists.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//Provider Source Folder Path
string SourceFolder = @"C:\Source\";
//Provide Destination Folder path
string DestinationFolder = @"
C:\Destination\";

var files = new DirectoryInfo(SourceFolder).GetFiles("
*.*");

//Loop throught files and copy to destination folder, overwrite if exists
foreach (FileInfo file in files)
{
file.CopyTo(DestinationFolder + file.Name,true);
}

}
}
}

How to take Differential backup of all the Databases on SQL Server Instance - SQL Server Tutorial

$
0
0

Scenario:

You are working as SQL Server DBA or developer and you need to prepare script that can take the differential backup of all the databases on SQL Server Instance. 

Below script can be used to take the differential backup of all the database you like. By simply making changes to select query for database name, you can include of exclude the database you take part or not take part in differential backup. I have excluded system database by using database_id>4 in where clause.


USE MASTER
GO
DECLARE @BackupPath varchar(100)
--Provide the backup path
SET @BackupPath = 'C:\Backup\'
DECLARE @DatabaseName ASvarchar(128)

DECLARE Cur CURSORFOR
--Change the select query for the DBs you like to backup
SELECT
name
FROM sys.databases
WHERE database_id>4


OPEN Cur
FETCHNEXTFROM Cur INTO @DatabaseName
WHILE@@FETCH_STATUS = 0
BEGIN
DECLARE @SQLvarchar(max) = NULL
DECLARE @DBNamewithDateTime varchar(128) = NULL
SET @DBNamewithDateTime = @DatabaseName + '_' + REPLACE(CAST(GETDATE()
ASdate), '-', '') + '_' + REPLACE(CAST(CAST(GETDATE() AStime)
ASchar(8)), ':', '')

SET @SQL = 'BACKUP DATABASE [' + @DatabaseName + '] TO DISK = N''' +
@BackupPath + '' + @DBNamewithDateTime + '.DIF''
WITH DIFFERENTIAL ,NOFORMAT, NOINIT, NAME = N'
'' +
              @DBNamewithDateTime 
+ '-Diff Backup'',
SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10'


PRINT @SQL
EXEC (@SQL)
FETCHNEXTFROM Cur INTO @DatabaseName
END
CLOSE Cur
DEALLOCATE Cur

I execute above script and it took differential backup of all user databases to Backup Folder. You can also use this script in SQL Server Agent and schedule it as per your need.

C# - How to Move files from a folder to Another Folder in C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer, you need to create a program that should move the files from source folder to destination folder. 

Below code can be used to move all the files from a folder to another folder.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
static void Main(string[] args)
{
//Provider Source Folder Path
string SourceFolder = @"C:\Source\";
//Provide Destination Folder path
string DestinationFolder = @"C:\Destination\";

var files = new DirectoryInfo(SourceFolder).GetFiles("*.*");

//Loop throught files and Move to destination folder
foreach (FileInfo filein files)
{

file.MoveTo(DestinationFolder+file.Name);

}

}
}
}

C# - File.MoveTo Does not work - Cannot create a file when that file already exists. - C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer and you need to write a program that should move all the files from a folder to another folder. You wrote the code and used file.MoveTo, it moved the files first. Later when you try to move the next batch, it failed with error "Cannot create a file when that file already exists.".

That means file already exists in the destination folder, you need to modify your script. We can delete the file if already exists and then move the file to destination folder.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//Provider Source Folder Path
string SourceFolder = @"C:\Source\";
//Provide Destination Folder path
string DestinationFolder = @"
C:\Destination\";

var files = new DirectoryInfo(SourceFolder).GetFiles("
*.*");

//Loop throught files and Move to destination folder
foreach (FileInfo file in files)
{
//delete file if already exists
File.Delete(DestinationFolder + file.Name);

//Move the file to destination folder
file.MoveTo(DestinationFolder+file.Name);

}

}
}
}

C# - How to move and rename files to another folder by adding datetime to file name by C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer, you need to create a program that should move all the files from a folder to destination folder. While it moves the files, it should rename the files and add datetime to each file.

The C# code can be used to move and rename files from a folder to another folder and will add date-time to each file.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{

try
{
//Provider Source Folder Path
string SourceFolder = @"C:\Source\";
//Provide Destination Folder path
string DestinationFolder = @"
C:\Destination\";

//datetime variable to use as part of file name
string datetime = DateTime.Now.ToString("
yyyyMMddHHmmss");

var files = new DirectoryInfo(SourceFolder).GetFiles("
*.*");

//Loop throught files and Move to destination folder
foreach (FileInfo file in files)
{

string fileExt = "
";
fileExt = Path.GetExtension(file.Name);

//Move the file to destination folder after adding datetime
file.MoveTo(DestinationFolder + file.Name.Replace(fileExt,"
") + "_" + datetime + fileExt);

}

}
catch(IOException Exception)
{
Console.Write(Exception);
}
}

}
}

C# - How to Copy files from a folder to another folder and add date-time to file names in C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer, you need to write a program that should copy the files from a folder to another folder, while it copies the file, it should add date-time to each file name it copies to destination folder.


Below C# Script can be used to copy all the files from a folder to another folder and add date-time to destination copied file names.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{

try
{
//Provider Source Folder Path
string SourceFolder = @"C:\Source\";
//Provide Destination Folder path
string DestinationFolder = @"
C:\Destination\";

//datetime variable to use as part of file name
string datetime = DateTime.Now.ToString("
yyyyMMddHHmmss");

var files = new DirectoryInfo(SourceFolder).GetFiles("
*.*");

//Loop throught files and Copy to destination folder
foreach (FileInfo file in files)
{

string fileExt = "
";
fileExt = Path.GetExtension(file.Name);

//Copy the file to destination folder after adding datetime
file.CopyTo(DestinationFolder + file.Name.Replace(fileExt,"
") + "_" + datetime + fileExt);

}

}
catch(IOException Exception)
{
Console.Write(Exception);
}
}

}
}

C# - How to Import or Load Text file to SQL Server Table by using C Sharp

$
0
0

Scenario: Download Script

You are working as C# developer, You need to write a program that should read the text file (CSV) file and load the data to SQL Server table. Once the file data is loaded to SQL server table, the file need to be moved to Archive Folder.

Step 1: 
Let's create table in database as per our file metadata. I have the file with id and CourseName as shown below.

Load or Import Text file to SQL Server Table by using C Sharp


Create Table statement.

CREATETABLE dbo.TechBrothersITCourse (
id INT
,CourseName VARCHAR(100)
)


Step 2: Create New project and choose Console Application.

Below code can be used to load the text file to SQL Server Table and move the file to Archive folder once loaded.

I have create variable so you can change the values as per your requirement. Let's say if you have the file with pipe ( | ) delimited. You can change filedelimiter value to "|";

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{

try
{

//Declare Variable and set values
//provide input folder
string SourceFolder = @"C:\Source\";
//provide file name
string SourceFileName = "
TechBrothersIT.txt";
//provide the table name in which you would like to load data
string TableName = "
dbo.TechBrothersITCourse";
//provide the file delimiter such as comma,pipe
string filedelimiter = "
,";
//provide the Archive folder where you would like to move file
string ArchiveFodler = @"
C:\Archive\";

//Create Connection to SQL Server
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = (local); Initial Catalog =TechBrothersIT; "
+ "
Integrated Security=true;";

System.IO.StreamReader SourceFile =
new System.IO.StreamReader(SourceFolder+SourceFileName);

string line = "
";
Int32 counter = 0;

SQLConnection.Open();
while ((line = SourceFile.ReadLine()) != null)
{
//skip the header row
if (counter > 0)
{
//prepare insert query
string query = "
Insert into " + TableName +
"
Values ('" + line.Replace(filedelimiter, "','") + "')";

//execute sqlcommand to insert record
SqlCommand myCommand = new SqlCommand(query, SQLConnection);
myCommand.ExecuteNonQuery();
}
counter++;
}

SourceFile.Close();
SQLConnection.Close();

//Move the file to Archive folder
File.Move(SourceFolder+SourceFileName, ArchiveFodler + SourceFileName);

}
catch(IOException Exception)
{
Console.Write(Exception);
}
}

}
}

Step 3: Save the script and Execute
Once you execute the program, it should read the file and load the data to table as shown below.
C# - Import Text file to SQL Server Table by using C Sharp




How to Drop or delete all User Databases on SQL Server Instance - SQL Server Tutorial

$
0
0

Scenario:

You are working as DBA or developer, you need to generate scripts that should be able to drop all the users databases on SQL server Instance. 

Also you can made modification to Select query to include or exclude database which you would like to drop.

Below script can be used to drop all the databases on SQL Server Instance, It will kill connections to databases and then drop them.


USE MASTER
GO

DECLARE @DatabaseName ASVARCHAR(128)

DECLARE Cur CURSORFOR

--Get list of Databases You want to drop
SELECT name from
sys.databases
where database_id>4

OPEN Cur
FETCHNextFROM Cur INTO @DatabaseName
WHILE@@FETCH_STATUS = 0
BEGIN

--Inner Cursor Start
--Kill all user connections to database
DECLARE @Spid INT
DECLARE KillProcessCur CURSORFOR
SELECT spid
FROM sys.sysprocesses
WHERE dbid = DB_ID(@DatabaseName)
OPEN KillProcessCur
FETCHNextFROM KillProcessCur INTO @Spid
WHILE@@FETCH_STATUS = 0
BEGIN
DECLARE @SQLVARCHAR(500)=NULL
SET @SQL='Kill ' + CAST(@Spid ASVARCHAR(5))
EXEC (@SQL)
PRINT'ProcessID =' + CAST(@Spid ASVARCHAR(5))
+ ' killed successfull'
FETCHNextFROM KillProcessCur INTO @Spid
END
CLOSE KillProcessCur
DEALLOCATE KillProcessCur
--Inner Cursor Ends

--Outer Cursor: Drop Database
DECLARE @SQLDropDB NVARCHAR(MAX)=NULL
SET @SQLDropDB='Drop Database ['+@DatabaseName+']'
Print @SQLDropDB
EXEC (@SQLDropDB)
FETCHNextFROM Cur INTO @DatabaseName
END
CLOSE Cur
DEALLOCATE Cur

--Get list of existing databases
Select name as DBName,@@serverName AS ServerName
from sys.databases

How to get Information about your Backups and Save into SQL Server Table - SQL Server Tutorial

$
0
0

Scenario:

You are working as SQL Server DBA or developer, you need to get Database Name from backups files or maybe other information such as

  • Who performed this backup
  • Which Server wrote this backup
  • Size of backup in bytes
  • Version of Database
  • Either is backup is taken by compression enable or not
  • Compatibility level of the database from which backup was created
and tons of other information. Not a big deal, We can use below statement to get above information.

RESTORE HEADERONLY FROMDISK='c:\backup\Yourbackupfile.bak'

That is great, but think about a situation when you have a lot of backup files and you would like to gather information and store in a table. 

The below script can be used to save RESTORE HEADERONLY information to table for all the backup files which exists in backup folder you have provided. 


--provide the folder path where backups are present
DECLARE @BackupFolder VARCHAR(128)
SET @BackupFolder='C:\Backup\'

--Get Backup files informaiton in temp table
IF OBJECT_ID('tempdb..#BackupFileList') ISNOTNULL
DROPTABLE #BackupFileList

IF OBJECT_ID('tempdb..#RestoreHeaderOnly') ISNOTNULL
DROPTABLE #RestoreHeaderOnly
--Create temp table to Store HeaderOnly Information from Database
CreateTable #RestoreHeaderOnly(
BackupName nvarchar(128) ,
BackupDescription nvarchar(255) ,
BackupType smallint ,
ExpirationDate datetime ,
Compressed bit ,
Positionsmallint ,
DeviceType tinyint ,
UserName nvarchar(128) ,
ServerName nvarchar(128) ,
DatabaseName nvarchar(128) ,
DatabaseVersion int ,
DatabaseCreationDate datetime ,
BackupSize numeric(20,0) ,
FirstLSN numeric(25,0) ,
LastLSN numeric(25,0) ,
CheckpointLSN numeric(25,0) ,
DatabaseBackupLSN numeric(25,0) ,
BackupStartDate datetime ,
BackupFinishDate datetime ,
SortOrder smallint ,
CodePage smallint ,
UnicodeLocaleId int ,
UnicodeComparisonStyle int ,
CompatibilityLevel tinyint ,
SoftwareVendorId int ,
SoftwareVersionMajor int ,
SoftwareVersionMinor int ,
SoftwareVersionBuild int ,
MachineName nvarchar(128) ,
Flags int ,
BindingID uniqueidentifier ,
RecoveryForkID uniqueidentifier ,
Collation nvarchar(128) ,
FamilyGUID uniqueidentifier ,
HasBulkLoggedData bit ,
IsSnapshot bit ,
IsReadOnly bit ,
IsSingleUser bit ,
HasBackupChecksums bit ,
IsDamaged bit ,
BeginsLogChain bit ,
HasIncompleteMetaData bit ,
IsForceOffline bit ,
IsCopyOnly bit ,
FirstRecoveryForkID uniqueidentifier ,
ForkPointLSN numeric(25,0) NULL ,
RecoveryModel nvarchar(60) ,
DifferentialBaseLSN  numeric(25,0) NULL ,
DifferentialBaseGUID uniqueidentifier ,
BackupTypeDescription nvarchar(60) ,
BackupSetGUID uniqueidentifier NULL ,
CompressedBackupSize bigint ,
containment tinyint notNULL ,
KeyAlgorithm nvarchar(32) ,
EncryptorThumbprint varbinary(20) ,
EncryptorType nvarchar(32))


--create temp table to save backup files
--I am considering all backups are in root level
--if they are in sub folders, change your select query for #BackupFileList
CREATETABLE #BackupFileList (
Id intidentity(1,1),
BackupFile nvarchar(255),
Depthsmallint,
FileFlag bit)

INSERTINTO #BackupFileList (BackupFile,Depth,FileFlag)
EXEC xp_dirtree @BackupFolder, 10, 1

--Use Cursor to loop throught backups files
--to get header information and insert into temp table
Declare @BackupFile VARCHAR(500)

DECLARE Cur CURSORFOR
SELECT BackupFile from #BackupFileList
where fileflag=1

OPEN Cur
FETCHNextFROM Cur INTO @BackupFile
WHILE@@FETCH_STATUS = 0
BEGIN

insertinto #RestoreHeaderOnly
EXEC('RESTORE HEADERONLY FROM DISK = '''+@BackupFolder+@BackupFile+'''')


FETCHNextFROM Cur INTO @BackupFile
END
CLOSE Cur
DEALLOCATE Cur


--Check the Restore HeaderOnly information from temp table for all the backups files
select * From #RestoreHeaderOnly

I execute above query and it was able to get the information from backups files and insert into temp table. Here is partial snapshot as can't show all the columns.
How to get information such as Database Name,Version,Server Name from backup files and insert into SQL Server Table


How to Restore Databases from full backup files from a folder to SQL Server Instance - SQL Server

$
0
0

Scenario:

You are working as SQL Server DBA or developer, you need to prepare script that should read the backup files from a folder and then restore as database to SQL Server Instance.

Following things to consider for  below scripts.

  1. The backup files are in sitting in root folder, if there are sub folders you have to make change to script to include those files.
  2. The script consider that there is only one Data file for each database. If you have more than one Data File, you need to make a change to script.
  3. You need to provide Data File location and Log file location to restore database from backup file.
  4. If Database is already there, it will not overwrite. You can change Restore statement to include overwrite clause if you like.


You can comment out the EXEC(@SQLRestore) line, so it will not start restore. The print statement is there that will print out the sql scripts for you so you can run them manually if you like.


--Provide the folder path where backups are present
DECLARE @BackupFolder VARCHAR(128)
SET @BackupFolder='C:\Backup\'

--Provide the data and log files paths
--where you would like to restore databases

Declare @DataFilesPath VARCHAR(128)
Declare @LogFilesPath VARCHAR(128)

SET @DataFilesPath='C:\Backup\Data\'
SET @LogFilesPath='C:\Backup\Log\'

--Get Backup files informaiton in temp table
IF OBJECT_ID('tempdb..#BackupFileList') ISNOTNULL
DROPTABLE #BackupFileList

--Drop temp table if exits
IF OBJECT_ID('tempdb..#RESTOREFILELISTONLY') ISNOTNULL
DROPTABLE #RESTOREFILELISTONLY

IF OBJECT_ID('tempdb..#RestoreHeaderOnly') ISNOTNULL
DROPTABLE #RestoreHeaderOnly

CREATETABLE #BackupFileList (
Id intidentity(1,1),
BackupFile nvarchar(255),
Depthsmallint,
FileFlag bit)



--Store Backup information
CreateTable #RestoreHeaderOnly(
BackupName nvarchar(128) ,
BackupDescription nvarchar(255) ,
BackupType smallint ,
ExpirationDate datetime ,
Compressed bit ,
Positionsmallint ,
DeviceType tinyint ,
UserName nvarchar(128) ,
ServerName nvarchar(128) ,
DatabaseName nvarchar(128) ,
DatabaseVersion int ,
DatabaseCreationDate datetime ,
BackupSize numeric(20,0) ,
FirstLSN numeric(25,0) ,
LastLSN numeric(25,0) ,
CheckpointLSN numeric(25,0) ,
DatabaseBackupLSN numeric(25,0) ,
BackupStartDate datetime ,
BackupFinishDate datetime ,
SortOrder smallint ,
CodePage smallint ,
UnicodeLocaleId int ,
UnicodeComparisonStyle int ,
CompatibilityLevel tinyint ,
SoftwareVendorId int ,
SoftwareVersionMajor int ,
SoftwareVersionMinor int ,
SoftwareVersionBuild int ,
MachineName nvarchar(128) ,
Flags int ,
BindingID uniqueidentifier ,
RecoveryForkID uniqueidentifier ,
Collation nvarchar(128) ,
FamilyGUID uniqueidentifier ,
HasBulkLoggedData bit ,
IsSnapshot bit ,
IsReadOnly bit ,
IsSingleUser bit ,
HasBackupChecksums bit ,
IsDamaged bit ,
BeginsLogChain bit ,
HasIncompleteMetaData bit ,
IsForceOffline bit ,
IsCopyOnly bit ,
FirstRecoveryForkID uniqueidentifier ,
ForkPointLSN numeric(25,0) NULL ,
RecoveryModel nvarchar(60) ,
DifferentialBaseLSN  numeric(25,0) NULL ,
DifferentialBaseGUID uniqueidentifier ,
BackupTypeDescription nvarchar(60) ,
BackupSetGUID uniqueidentifier NULL ,
CompressedBackupSize bigint ,
containment tinyint notNULL ,
KeyAlgorithm nvarchar(32) ,
EncryptorThumbprint varbinary(20) ,
EncryptorType nvarchar(32))


--Create Temp Table for DB files
Createtable #RESTOREFILELISTONLY(
LogicalName NVARCHAR(128),
PhysicalName NVARCHAR(260),
Type CHAR(1),
FileGroupName NVARCHAR(128),
Sizenumeric(20,0),
MaxSize numeric(20,0),
Field bigint,
CreateLSN numeric(25,0),
DropLSN numeric(25,0),
UniqueId uniqueidentifier,
ReadonlyLSN numeric(25,0),
ReadWriteLSN numeric(25,0),
BackupSizeInBytes BigInt,
SourceBlockSize Int,
FileGroupId int,
LogGroupGUID uniqueidentifier,
DifferentialBaseLSN numeric(25,0),
DifferentialBaseGUID uniqueidentifier,
IsReadOnly bit,
IsPresent bit,
TDEThumprint varbinary(32))

--Save backup files into temp table
INSERTINTO #BackupFileList (BackupFile,Depth,FileFlag)
EXEC xp_dirtree @BackupFolder, 10, 1

--Select * FROM #BackupFileList

--Use Cursor to loop throught backups files and restore
Declare @BackupFile VARCHAR(500)

DECLARE Cur CURSORFOR
SELECT BackupFile from #BackupFileList
where fileflag=1

OPEN Cur
FETCHNextFROM Cur INTO @BackupFile
WHILE@@FETCH_STATUS = 0
BEGIN

Truncatetable #RESTOREFILELISTONLY

--Insert data from RESTORE FILELISTONLY
insertinto #RESTOREFILELISTONLY
EXEC('RESTORE FILELISTONLY FROM DISK = '''+@BackupFolder+@BackupFile+'''')

insertinto #RestoreHeaderOnly
EXEC('RESTORE HEADERONLY FROM DISK = '''+@BackupFolder+@BackupFile+'''')
--Select * From #RESTOREFILELISTONLY

Declare @LogFileName NVARCHAR(128)=NULL
Declare @DataFileName NVARCHAr(128)=NULL
Declare @DBName NVARCHAR(128)=NULL
--We are considering we have a log and single data file
SET @LogFileName=(Select logicalName from #RESTOREFILELISTONLY where type='L')
SET @DataFileName=(Select logicalName from #RESTOREFILELISTONLY where type='D')
SET @DBName=(Select DatabaseName from #RestoreHeaderOnly)


--Prepare Restore Statement
Declare @SQLRestore NVARCHAR(MAX)
SET @SQLRestore='RESTORE DATABASE "' +@DBName+'"
FROM DISK='
''+@BackupFolder+@BackupFile+'''
WITH
MOVE '
''+@DataFileName+''' TO '''+@DataFilesPath+@DataFileName+'.mdf'',
MOVE '
''+@LogFileName+''' TO '''+@LogFilesPath+@LogFileName+'.ldf'''

--Execute SQL to Restore DBs
Print @SQLRestore
EXEC(@SQLRestore)

Truncatetable #RestoreHeaderOnly
FETCHNextFROM Cur INTO @BackupFile
END
CLOSE Cur
DEALLOCATE Cur

I executed above code in my environment and it was able to restore backup files from a folder to my SQL Server Instance.

Note: Always test the scripts in Development environment before you execute in QA,UAT and Production.

Viewing all 1927 articles
Browse latest View live