Skip to main content

Posts

Showing posts from September, 2023

How to Restore a SQL Server Database from a Backup File

If the restored database has the name '@DatabaseName', you'll need to rename it manually to 'Autocom3_Filial_Movimento_Mensal_2023_03'. You can do this by right-clicking on the database name in SQL Server Management Studio and selecting Rename, or by using the following SQL command:Restoring a database from a backup file is a common task for database administrators. In this article, we'll walk through the steps to restore a SQL Server 2008 R2 database from a backup file using T-SQL. This is a straightforward process, but it's important to do it correctly to avoid errors and ensure that the data is fully recovered. Prerequisites SQL Server 2008 R2 installed A backup file of the database (.bkp) Steps to Restore a Database 1. Define Variables for Backup and Database Names We need to specify the path to the backup file and the name we want to give to the restored database.  -- Set the backup file path DECLARE @BackupFile NVARCHAR(500) = 'C:\autocom3_temp\aut

Count the Number of Rows in All Tables in a SQL Server Database

If you're working with SQL Server databases, you might often find yourself needing to quickly get the count of rows for each table within a database. This can be helpful for various tasks such as data analysis, debugging, or performance tuning. In this article, we will cover a SQL script that will help you to fetch the number of rows in all the tables in a SQL Server database.  -- Switch to your database USE YourDatabaseName; -- Replace 'YourDatabaseName' with the name of your database -- Declare variables DECLARE @TableName AS VARCHAR(255) DECLARE @SQL AS NVARCHAR(MAX) -- Create a temporary table to store the results CREATE TABLE #TableCounts (     TableName VARCHAR(255),     RecordCount INT ) -- Create a cursor to loop through all the tables DECLARE TableCursor CURSOR FOR  SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' -- Open the cursor and fetch the first table into @TableName OPEN TableCursor FETCH NEXT FROM TableCursor INTO @T