To check the date and time SQL Server last restarted, execute the T-SQL script below.
SELECT sqlserver_start_time FROM sys.dm_os_sys_info
Recovery models are designed to control transaction log maintenance. A recovery model is a database property that controls how transactions are logged, whether the transaction log requires (and allows) backing up, and what kinds of restore operations are available. Three recovery models exist: simple, full, and bulk-logged. Typically, a database uses the full recovery model or simple recovery model. A database can be switched to another recovery model at any time.
Use the script below to view the database recovery model.
SELECT name AS [Database Name],
recovery_model_desc AS [Recovery Model]
FROM sys.databases
GO
The following table summarizes the three recovery models.
Locking is a mechanism used by the SQL Server Database Engine to synchronize access by multiple users to the same piece of data, at the same time. In simpler words, it maintains the integrity of data by protecting (or preventing) access to the database object.
LCK_M_BU
Occurs when a task is waiting to acquire a Bulk Update (BU) lock.
LCK_M_IS
Occurs when a task is waiting to acquire an Intent Shared (IS) lock.
LCK_M_IU
Occurs when a task is waiting to acquire an Intent Update (IU) lock.
LCK_M_IX
Occurs when a task is waiting to acquire an Intent Exclusive (IX) lock.
LCK_M_S
Occurs when a task is waiting to acquire a Shared lock.
LCK_M_SCH_M
Occurs when a task is waiting to acquire a Schema Modify lock.
LCK_M_SCH_S
Occurs when a task is waiting to acquire a Schema Share lock.
LCK_M_SIU
Occurs when a task is waiting to acquire a Shared With Intent Update lock.
LCK_M_SIX
Occurs when a task is waiting to acquire a Shared With Intent Exclusive lock.
LCK_M_U
Occurs when a task is waiting to acquire an Update lock.
LCK_M_UIX
Occurs when a task is waiting to acquire an Update With Intent Exclusive lock.
LCK_M_X
Occurs when a task is waiting to acquire an Exclusive lock.
When you want to rename your database and you hit the error below, you need to set the database to Single User Mode. After you rename your database, then you set the database back to Multi-User mode.
Msg 5030, Level 16, State 2, Line 1
The database could not be exclusively locked to perform the operation
Follow the steps below to rename your database.
ALTER DATABASE OLD_DBName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
2. Rename the Database
ALTER DATABASE OLD_DBName MODIFY NAME = NEW_DBNAME;
3. Set the database to Multi-user mode
ALTER DATABASE NEW_DBNAME SET MULTI_USER WITH ROLLBACK IMMEDIATE;
You may check out this blog post where I show a better way to rename a database.
Cheers!
Service Broker in Microsoft SQL Server 2005 is a new technology that provides messaging and queuing functions between instances. The basic functions of sending and receiving messages forms a part of a “conversation”. Each conversation is considered to be a complete channel of communication. Each Service Broker conversation is considered to be a dialog where two participants are involved.
--Enable Service Broker
ALTER DATABASE DB_Name SET ENABLE_BROKER;
--Verify status of Service Broker. A status of 1 means that it is enabled (0 means it is disabled)
SELECT is_broker_enabled
FROM sys.databases
WHERE name = 'DB_Name'
The other day, I was troubleshooting a database slowness issue when the lead application developer asks me whether or not there are any SQL Jobs running during that time. The T-SQL script below helped me to retrieve that info. This T-SQL script will check the SQL Agent Job history.
SELECT
j.name AS 'JobName',
run_date,
run_time,
msdb.dbo.agent_datetime(run_date, run_time) AS 'RunDateTime'
FROM msdb.dbo.sysjobs j
INNER JOIN msdb.dbo.sysjobhistory h
ON j.job_id = h.job_id
WHERE j.enabled = 1 --Only Enabled Jobs
ORDER by JobName, RunDateTime DESC
This is the first PowerShell script that I wrote. I was inspired to start using PowerShell after I met with one of our developers. He creates scripts to automate repetitive administrative tasks (e.g. daily system health check). I asked the developer if he learned writing PowerShell from a book or a training class. He said that he neither read any book nor attend a PowerShell training class. Instead, he told me that he just knows what he wanted to achieve and then he searched the internet on how to achieve it. In other words, he just Googled the codes.
I always wanted to learn PowerShell. As a DBA, I think it would be beneficial to use this powerful tool. I read books about PowerShell and did the exercises but I feel I never progressed and I’m still not able to create anything.
So I tried to do what the developer told me. First, I started to think what I want to achieve and that is to send disk space usage of our Database Servers to my email. This is so that I won’t have to login to our DB servers everytime.
Below is the PowerShell script.
#.SYNOPSIS
# Sends Daily Disk Space Usage Report
#
#EXAMPLE
#.\Send-DiskSpaceUsageReport.ps1
#
$smtpServer = "Fsmtp.our.property.com.sg"
$smtpFrom = "NXPOPARVRAPPLE@nhg.local"
$smtpTo = "valenciajec@ncs.com.sg"
$messageSubject = "OPAS TTSH Daily Disk Space Usage Report"
[string]$messagebody = ""
$logs = Get-Content D:\DBA\DB_Health_Checks_Node1\6.DiskUsage_Node1_/TTSH.txt, \\10.240.xx.xx\d$\DBA\DB_Health_Checks_Node2\2.DiskUsage_Node2_TTSH.txt
foreach ($log in $logs )
{
$messagebody = $messagebody + $log + "`r`n"
}
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($smtpFrom,$smtpTo,$messagesubject,$messagebody)
This script will add a message body to emails sent from script. I have a SQL Server Agent job that generates the text file that contains the disk space usage report. So basically, the PowerShell script will get the contents of the text file and add it to the message body of the email.
The next step is to create a Scheduled Task to run the PowerShell script.
Open Task Scheduler
Open Task Scheduler and Create a new task. Name it and set your security options. Check "Run with highest privileges" as our scripts need to run as admin. Choose “Run whether user is logged on or not.”
Set Triggers
Create your Action
Click on Actions tab and click New.
Action: Start a program
Program /script: PowerShell.exe
You don’t need to put a path as it should already be on your system
Set Argument
You first need to set the ExecutionPolicy. There are two options to do that either you set the ExecutionPolicy on the machine or on a per-script basis. I will only set it on a per-script basis but If you want to set the execution policy globally, you can issue this command from within PowerShell.
Set-ExecutionPolicy Unrestricted
To set the ExecutionPolicy on a per script basis, put the line below on the Add arguments (change the file name to your script’s file name.ps1)
-ExecutionPolicy Bypass -File D:\DBA\Scripts\PowerShell\Send-DiskSpaceUsageReport.ps1
Indicate the path of your script in the Start in(optional)
Change Settings
I encountered the error “Launch request ignored, instance already running (154257)”and the task failed to run. To resolve this issue, I changed the setting to “Stop the existing instance”
Save and Test
When you are writing a SELECT statement and you just want to limit the number of columns, you would use the sp_help stored procedure to research the underlying table structure as shown below.
The sp_help system stored procedure will return all the data about a particular table when you pass the table name into the stored procedure.
But If you don't want to sort through all that information, it is possible to get only the names of the columns by executing a query that selects all columns with a false WHERE clause as shown below.
SELECT *
FROM [HumanResources].[Employee]
WHERE 1=0
This query tells SQL Server to return all the columns and rows where one equals zero. Because one can never equal zero, SQL Server will return the column names from the table with no data.
Do you have a recent backup of all your SQL Server databases? Use the script below to check if you have.
SELECT B.name as Database_Name, ISNULL(STR(ABS(DATEDIFF(day, GetDate(),
MAX(Backup_finish_date)))), 'NEVER') as DaysSinceLastBackup,
ISNULL(Convert(char(10), MAX(backup_finish_date), 101), 'NEVER') as LastBackupDate
FROM master.dbo.sysdatabases B LEFT OUTER JOIN msdb.dbo.backupset A
ON A.database_name = B.name AND A.type = 'D' GROUP BY B.Name ORDER BY B.name