SQL Server -Database Backup Report using PowerShell and T-SQL

In the previous articles, we discussed several ways of taking backup and testing the restore process to ensure the integrity of the backup file.

In this article, we’re going to discuss the importance of the database backup reporting. This kind of reporting will be designed to eliminate any unnecessary risk that may arise with the safety and security of information. This is the reason, the high-level report; Daily Health Check report will be generated and sent to the SME or to the DBA responsible for IT Infra management.

Database backups are a vital component for most of the database administrators regardless what backup tool is in place and how the data backup process is all about backing up the data to the disk, to the tape or to the cloud.

In general, administrators are very much concerned with getting the report daily and also any alerts as per the defined SLAs. Administrators rely on the backup report to understand and how the backups are doing and always wanted to safeguard the data

The other area, we will cover, is the online backup; it is increasingly becoming the default choice for many small businesses databases. A database backup report is an important document which reveals the specific piece of information about the status of the data. In general, the generation reports have become a standard practice for any business who values their data.

A backup report should be produced after each backup job has run. The report provides detailed information including what was backed up, what can be restored and information about the backup media. Some of the information provided is specific to each backup type.

The following are the three important parameters that need to be reviewed at regular intervals of time are:

  1. Backup failure jobs

    This is the most important metric to be measured and in most cases, it requires immediate attention and action. For test or dev environments, this could wait for being taking an action based on the SLA

  2. Capacity planning and forecasting

    The other report generally circulated every day is the disk space utilization report. Proactive monitoring of storage would prevent most of the backup failures and it helps to forecast the data growth. In turn, this may reduce many unforeseen disk space-related issues.

  3. Performance

    Backup performance is the important metric to measure the overall health of the system. It gives a heads-up for many hidden issues such as hardware resource problem, device driver issues, network throughput problem, software problem etc:-

 

Further reading…

Backup report

 

 

Advertisements
Posted in Uncategorized | Leave a comment

Getting Started with Mssql-cli tool

A recent announcement on the release of several SQL Server tools has raised expectations across various groups. Product requirements and business are almost always a trade-off, and striking the right balance in a product in terms of the toolset is a sign of a successful product. After testing the SQL Operations Studio, I feel that it’s a promising tool for many developers, administrators, and DevOps specialists. In my opinion, the mssql-cli tool adds another feature to SQL Server in order to make it a leading database product.

Microsoft announced mssql-cli, a SQL Server user-friendly, command line interactive tool hosted by the dbcli-org community on GitHub. It’s an interactive, cross-platform command line query tool. The public preview release of mssql-cli is available for testing. mssql-cli is based on Python and the command-line interface projects such as pgcli and mycli. Microsoft released this tool under the OSF (Open Source Foundation) BSD 3 license. We can find its source code on GitHub. Now, the tool and the code are available for public preview. The tool is officially supported on Windows, Linux, and MacOS, and is compatible with Python versions 2.7, 3.4, and higher.

Mssql-cli improves the interactive CLI experience for T-SQL and includes support for SQL Server, MySQL, and PostgreSQL. The SQL Tools Service is the micro-service that forms the backend and based on .NET SDK Framework.

Mssql-cli is a little ahead of sqlcmd in terms of functionality and enhancements. Some of these features are introduced below:

Features

  1. T-SQL IntelliSense
    • This provides an array of keyword references that can be easily accessible during the development process.
    • The parameter or metadata population is contextual.
    • It also provides a quick reference.
  2. Syntax highlighting
    • This feature helps in identifying the troubleshooting of typo or syntax errors.
    • It helps to complete keywords and snippets automatically, thus, improving efficiency.
    • Autosuggestion and auto-completion of tasks where needed are available.
  3. Query history
    • It provides a way to store the history.
    • This tool is no different than many other editors—use the up/down arrow keys to select the desired SQL statement.
    • The advantage of this tool is to automatically suggest commands from the history.
  1. Configuration
    • A configuration file is used to configure the initial settings and parameters.
    • By default, the configuration file is stored to the following path:
        1. Important file location paths on Linux
          1. Configuration file – ~/.config/mssqlcli/config
          2. Log file ~/.config/mssqlcli/config/mssqlcli.log
          3. History file – ~/.config/mssqlcli/config/history
        2. Important file location paths on Windows
          1. Configuration file – %USERPROFILE%\AppData\Local\dbcli\mssqlcli\
          2. Log file – %USERPROFILE%\AppData\Local\dbcli\mssqlcli\mssqlcli.log
          3. History file – %USERPROFILE%\AppData\Local\dbcli\mssqlcli\history\
  2. Multi-line queries

Linebreaking within a query is very similar to what we have in SQL. To provide another example, in many languages, even shell languages, we can break up a single long command or a chain of commands into multiple lines. In PowerShell, we break the line with a backtick (`). In BAT/CMD, we use ^ to indicate that we have not yet done to issue commands to the shell.

  1. Mssql-cli modes

mssql-cli works in two very popular modes right out of the box: VI and EMACS. Those who are familiar with UNIX would instantly recognize these tools—text editors, to be precise. Most VI (and VIM—or VI Improved) users talk about “thinking in VI(M)”, which essentially means that the editor is so friendly and minimal that typing on it is almost the second nature to most VI users. If you’re one of them, you should feel right at home using this tool in the VI mode.

If you’re one of the EMACS users, you can enable or even customize this mode on mssql-cli. EMACS has a library of the LISP code that enhances EMACS and extends its capabilities.

Further reading mssql-cli

 

Posted in SQL tools | Tagged | Leave a comment

SQL Database Corruption: Causes, Prevention, Fixing Techniques

“I had a Database File and I want to attach this MDF file to SQL Server 2014. However, whenever I try to attach the file, I am receiving following error message :
The header for file ….\MSSQL\DATA\xxxx_data.mdf’ is not a valid database file header. The FILESIZE property is incorrect. (SQL Server Error 5172)”.

After surfing a lot, I found that MDF file has corruption in its header. I tried expert solution given in various forum websites but failed to fix header corruption, I am still getting the same error message. I have no idea how to deal with SQL database corruption. Can anybody suggest me any solution to fix this error? Thank you in advance!”

SQL Server stores its physical database in MDF file and the first page of this file, comprises the information of MDF file header. The header page keeps the information about the entire database like file signature, size etc. While attaching the MDF file in SQL Server, sometimes users encounter 5172 error code. This error generally occurs when the MDF file becomes corrupted or damaged. This error mismatches the information of the header and takes database into the inaccessible state. Thus, in this problem tackling blog, we are going to describe some easy and cost-efficient ways of dealing with SQL database corruption.

Before moving on to the Solution to fix database corruption, let us discuss what steps should not be taken if you are facing SQL database corruption.

What not to do?

Do not Reboot Server: Rebooting the server only can help to fix the minor issues from the OS end. If the issues are from server’s end then, reboot is not an appropriate solution. Rebooting system will put the database in offline mode and will detect it as a SUSPECT. This will make the situation worse.

Do not shutdown SQL Server: After identifying the master database corruption in SQL Server, every user tries to shut down the SQL Server. Yet, this is not a proper solution as the database become inaccessible via this.

Do not Detach/Re-attach Database: If corruption is present in the database, then detaching and re-attaching the database will make the recovery process much harder.

Do not Upgrade SQL Server: Upgrading SQL Server to fix the SQL database corruption is not an accurate method. Because upgrading the SQL Server version can create a new and major hurdle.

Do not Run Repair Command Instantly: The DBCC CHECKDB command only should be run when all other methods get failed. In many cases, this command takes users to permanent data loss condition. Thus, before executing this command, make sure you have correct knowledge of its syntax.

Solution to Fix SQL Database Corruption

Keeping regular backups and utilizing them later to recover the database in case of corruption or other disasters is the best option to deal with SQL database corruption. Nevertheless, it is not always a possible solution to restore all the data as there is always a missing portion of information between the last backup and time of disaster.

With SQL database repair program, it is possible to recover the entire data to the time of disaster or failure. The software is capable to repair corrupt MDF and NDF Server database. It has the capability to recover deleted SQL Server database table’s data.

The Final Note

There could be various factors that are responsible for the corrupt database like sudden shutdown, hardware failure, virus attack etc. In this write-up, we have covered various causes responsible for the corruption, What steps should not be taken when your database is in SUSPECT mode. The blog covers a quick solution to repair corrupt SQL database file.

Posted in SQL | Leave a comment

Backup and Restore Automation using SQLCMD and SQL Server agent

Database administrators are often requested to refresh a database, mostly to create a live copy of the production database to the test or development environment. This is done so that the development or the test environment closely resembles the production environment; this way, we prevent many undesirable issues when running the application in the production environment.

Many developers, at times, are required to write and debug code on the production copy of the database, so it makes more sense to refresh the database on regular basis.

Let’s build the process to automate the database refresh activity using a simple backup-and-restore method and scheduling it using SQL Server Agent.

  • Restore the database to the same server with a different name

 

  • Restore the database to a different server using sqlcmd and Robocopy utility

  • Schedule the job

 

Let’s take a closer look at the process to see how this works.

Continue reading Backup and Restore Automation using SQLCMD and SQL Server agent

 

Posted in SQL Server Backup | Tagged , , | Leave a comment

Backup Linux/windows SQL Server databases using PowerShell and Windows task scheduler

 

This article is an in-depth guide on how PowerShell can be used to maintain and manage SQL backup on Linux and Windows machines.

Here’s an outline of what this article is all about:

  • Introduction
  • Technical specifications
  • How to load SQL Server modules on Windows machine
  • Security – Credential Management
  • The objectives of Backup and Restore
  • Library Linkage
  • How SQL Server 2017 backup feature is used on Linux
  • And more …

Introduction

Tools to take SQL database backups, such as sqlcmd, SSMS, and PowerShell, are common to all platforms supported by SQL Server. In this post, I’m going to show how you can backup your SQL Server 2017 databases on a Linux machine using PowerShell.

Pre-requisites

  • RedHat Server 7.3 or CentOS 7.0 or higher
  • SQL Server 2017 or higher
  • SQL Server Management Studio (SSMS) 16.5 or higher

Flow Diagram

further reading

Backup Linux SQL Server databases using PowerShell

 

 

Posted in SQL Server Backup | Tagged , | Leave a comment

Data Recovery : Page level restore in SQL Server

In this article, we shall discuss the importance of understanding the internals of the page restoration for a database administrator. Most of the time, performing a page-level restore suffices for database availability. A good backup strategy is a key to recovery or restoration, and SQL Server provides us with an option to fix database pages at a granular level. Performing a page level restore in SQL Server is a clever option wherein the restoration of the entire VLDB database backup is not required.

Identifying the corruption and finding a solution is the key to successful restoration or recovery of the database. If the number of corrupted pages seems too large, and if the administrator feels that restoring the entire database from the most recent backup is a viable option, only in that case should the option be full restoration.

Page restore is a technique used to replace corrupted pages of information in a database with uncorrupted data from a backup. Page-level restore can be performed via SSMS or T-SQL. The intent of the restore is to fix one or more corrupted pages from the available backups. To identify corrupted pages, look for pages marked as “suspect” in the table, msdb syspect_pages.

In this series we will discuss the following topics:

  1. Introduction to page-level restore
  2. Different ways the data gets corrupted
  3. How to deal with corruption
  4. Restore a page from a full backup using SSMS and T-SQL
  5. And more…

Let’s explore the ways to corrupt and restore a page using a demo.

continue reading page level restore

Happy Learning!

 

Posted in Backup and Restore | Tagged , , , , , , | Leave a comment

Discuss smart database backup in SQL Server 2017

So far, we’ve discussed several phases of backup that starts with planning, creating, strategizing and implementing. In this article, we are going to see how database administrators can define the strategy to improve backup performance and efficiently manage backups in SQL Server 2017. The following are the topics of discussion:

  1. Discuss checkpoints
  2. Discuss the enhancements made in the Dynamic Management View (DMV) sys.dm_db_file_space_usagefor smart differential backups
  3. Discuss the enhancements made for the Dynamic Management function (DMF) sys.dm_db_log_stats  for smart transactional log backup
  4. Understand the functioning of smart differential backup and its internals
  5. Understand the Smart transaction log backup process and its internals
  6. T-SQL scripts
  7. And more…

 

Background

A checkpoint is a background process that writes dirty pages to disk. A checkpoint performs a full scan of the pages in the buffer pool, lists all the dirty pages that are yet to be written to the disk, and finally writes those pages to the disk. In SQL instances that do not have many dirty pages in the buffer pool, this is a trivial operation. However, with the SQL instances that have OLTP databases, use more memory and/or involve sequential scanning of all pages, the performance of the system could be impacted.

With SQL Server 2012, indirect checkpoints were introduced. In this case, the dirty page manager manages the dirty page list and generally keeps tracks of the all the dirty pages modifiers of the database. By default, it runs every 60 seconds and tracks the dirty pages that need to be flushed.

For example, if an indirect checkpoint is set to 120 seconds then individual pages would be flushed around 120 seconds after that they were made dirty. This will impact I/O. I/O also depends on the number of dirty modifiers lists of the database; we may even see a significant spike in the set target interval and see small hits as the pages change. This eliminates overhead to tracing and flushing the dirty pages which result in significant improvement in backup performance. To review further, go to the reference section below to understand more about the checkpoint and backup performance improvement process in detail.

On a database where an automatic checkpoint mode is set, tracing of the entire unit of the buffer pool is necessary to evaluate for possible dirty pages. On the other hand, with an indirect checkpoint, only those pages of the buffer pool that are dirtied have to be dealt with.

For example, let’s consider a system with 2 TB of memory that contains ~250 million buffer units and has 100 dirty pages. Assume that it requires 5 CPU cycles to trace and identify the status of each buffer unit. To traverse 250 million BUFs, it would require 1.25 trillion CPU cycles—and to what? Simply to find 100 positive dirty pages in the automatic checkpoint mode! However, 100 dirty pages are hardly anything with the indirect checkpoint mode. The entire buffer pool scanning time is eliminated.

further reading smart database backup

Happy learning!

 

Posted in SQL Server Backup | Tagged , , , | Leave a comment

Mssql-cli Command-Line Query Tool

A recent announcement on the release of several SQL Server tools has raised expectations across various groups. Product requirements and business are almost always a trade-off, and striking the right balance in a product in terms of the toolset is a sign of a successful product. After testing the SQL Operations Studio, I feel that it’s a promising tool for many developers, administrators, and DevOps specialists. In my opinion, the mssql-cli tool adds another feature to SQL Server in order to make it a leading database product.

Microsoft announced mssql-cli, a SQL Server user-friendly, command line interactive tool hosted by the dbcli-org community on GitHub. It’s an interactive, cross-platform command line query tool. The public preview release of mssql-cli is available for testing. mssql-cli is based on Python and the command-line interface projects such as pgcli and mycli. Microsoft released this tool under the OSF (Open Source Foundation) BSD 3 license. We can find its source code on GitHub. Now, the tool and the code are available for public preview. The tool is officially supported on Windows, Linux, and MacOS, and is compatible with Python versions 2.7, 3.4, and higher.

mssql-cli improves the interactive CLI experience for T-SQL and includes support for SQL Server, MySQL, and PostgreSQL. The SQL Tools Service is the micro-service that forms the backend and based on .NET SDK Framework.

mssql-cli is a little ahead of sqlcmd in terms of functionality and enhancements. Some of these features are introduced below:

Features

  1. T-SQL IntelliSense
    • This provides an array of keyword references that can be easily accessible during the development process.
    • The parameter or metadata population is contextual.
    • It also provides a quick reference.
  2. Syntax highlighting
    • This feature helps in identifying the troubleshooting of typo or syntax errors.
    • It helps to complete keywords and snippets automatically, thus, improving efficiency.
    • Autosuggestion and auto-completion of tasks where needed are available.
  3. Query history
    • It provides a way to store the history.
    • This tool is no different than many other editors—use the up/down arrow keys to select the desired SQL statement.
    • The advantage of this tool is to automatically suggest commands from the history.
  1. Configuration
    • A configuration file is used to configure the initial settings and parameters.
    • By default, the configuration file is stored to the following path:
      • Important file location paths on Linux
        • Configuration file – ~/.config/mssqlcli/config
        • Log file ~/.config/mssqlcli/config/mssqlcli.log
        • History file – ~/.config/mssqlcli/config/history
      • Important file location paths on Windows
        • Configuration file – %USERPROFILE%\AppData\Local\dbcli\mssqlcli\
        • Log file – %USERPROFILE%\AppData\Local\dbcli\mssqlcli\mssqlcli.log
        • History file – %USERPROFILE%\AppData\Local\dbcli\mssqlcli\history\
  2. Multi-line queries

Linebreaking within a query is very similar to what we have in SQL. To provide another example, in many languages, even shell languages, we can break up a single long command or a chain of commands into multiple lines. In PowerShell, we break the line with a backtick (`). In BAT/CMD, we use ^ to indicate that we have not yet done to issue commands to the shell.

  1. Mssql-cli modes

mssql-cli works in two very popular modes right out of the box: VI and EMACS. Those who are familiar with UNIX would instantly recognize these tools—text editors, to be precise. Most VI (and VIM—or VI Improved) users talk about “thinking in VI(M)”, which essentially means that the editor is so friendly and minimal that typing on it is almost the second nature to most VI users. If you’re one of them, you should feel right at home using this tool in the VI mode.

If you’re one of the EMACS users, you can enable or even customize this mode on mssql-cli. EMACS has a library of the LISP code that enhances EMACS and extends its capabilities.

 

Further reading mssql-cli

Happy Learing!

 

 

Posted in SQL tools | Tagged | Leave a comment

Automate SQL Server Database Restoration using bacpac with PowerShell or Batch techniques

Data is the key to your organization’s future, but if it’s outdated, irrelevant, or hidden then it’s no good. Maintenance and administration of databases take a lot of work. As database administrators, we often tend to automate most of these repetitive tasks. A database refresh is one of the most common tasks performed by most of the administrators as part of their daily routine.

Today, database refreshes are quite frequent because of Continuous Integration (CI) and Continuous Deployment (CD). In most of the cases, testing requires a separate but current production dataset to ensure the validity of the desired result.

In today’s world, we rely more on third-party tools to perform a Backup and Restore of databases. With many advanced tools and techniques, this is a pretty straightforward approach. Think of the real-world scenarios where customers rely on the native SQL Tools and techniques. Creating automated database refresh tasks regularly will have a huge impact on the quality of the release management cycles and would save a lot of time for the database administrators.

There are many ways to automate this, some of which are:

  • SQLCMD
  • PowerShell
  • SqlPackage

In this article, we about the following:

  • Details of Sqlcmd
  • The use of the cross-platform tool, Sqlpackage
  • Automation using Windows batch scripting
  • And more…

Using sqlcmd provides flexible ways to execute T-SQL and SQL script files. As its available on Linux, Windows, and Mac, this command line utility plays a vital role in managing the database restore operations in a DevOps pipeline.

PowerShell script to automatically create a bacpac file and restore the database using the created bacpac, using SqlPackage.exe

This section deals with the preparation of a PowerShell script to automate database restoration using the SqlPackage tool which is part of the SQL Server Data Tools suite.

The first step is to prepare and set the environment variables. The SqlPackage tool is installed under C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin. The script uses sqlcmd and SqlPackage tool; make sure that the path variable is updated accordingly.

  1. The input parameter section lists the source, target SQL databases instance and folder for extracting the bacpac file
  2. Create the bacpac file using export action type
  3. Select the latest bacpac file for further database restoration action
  4. Drop the destination database using the sqlcmd command
  5. Restore the database using import action type.

 

Continue reading sqlpackage

Happy Learning!

 

Posted in SQL Server Backup | Tagged , , | Leave a comment