Search This Blog

Monday, October 15, 2012

SQL Server DBA - Send e-mail notification when a database is not online


Checking the databases availability is one of the major task of a DBA which has to be performed  at regular intervals to make sure that the critical live databases are always online and fix them immediately if they are not online. This can be done in "n" number of ways and here is one such method.
The method that i am going to discuss below makes use of "Database Mail" option to send e-mails to the intended recipients when the process finds the status of the database which is not online.

After the "Database Mail" Option is configured all you have to do is to create a job with the below code and schedule it to run every five minutes or every one minute depending on the criticality of the databases that you are going to monitor.

Use this Code if you wish to receive the e-mail in HTML format:

if(select count(*) from sys.databases where state_desc<>'Online')>0

Begin

DECLARE @table  NVARCHAR(MAX) ;

SET @table =
    N'<H1>Offline Databases Report</H1>' +
    N'<table border="1">' +
    N'<tr><th>Database Name</th><th>Database Status</th></tr>' +
    CAST ( ( Select td=name, '',td=state_desc from sys.databases where state_desc<>'Online'
              FOR XML PATH('tr'), TYPE
    ) AS NVARCHAR(MAX) )    +
    N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail @profile_name='ProfileName', --Change to your Profile Name
      @recipients='email@domain.com;email1@domain.com', --Put the email address of those who want to receive the e-mail
    @subject = 'Offline Databases Report',
    @body = @table,
    @body_format = 'HTML' ;

END
Else Print 'All Databases are Online'
 
Use this Code if you wish to receive the e-mail in Plain Text format:
 
if(select count(*) from sys.databases where state_desc<>'Online')>0
Begin

EXEC msdb.dbo.sp_send_dbmail @profile_name='ProfileName', --Change to your Profile Name
      @recipients='email@domain.com;email1@domain.com', --Put the email address of those who want to receive the e-mail
    @subject = 'Offline Databases Report',
    @Query='Select rtrim(ltrim(name)) as DatabaseName,rtrim(ltrim(state_desc)) as CurrentDatabaseStatus from sys.databases where state_desc<>''Online'''
    
END
Else Print 'All Databases are Online'
 

Monday, May 14, 2012

SQL DBA : SQL 2005 - Move C2 Trace file from one Location to another Location


Move C2 Trace file from one Location to another Location :-


Create a Job With the Option of “ActiveX Script” (Select VB Script)


dim TracePath         ‘Declaring Variable for Assigning the Source path
dim FName              ‘Declaring Variable for Assigning the File Name

TracePath="G:\Microsoft SQL Server\MSSQL.1\MSSQL\Data\" ‘Source path of Trace File

   Set fso = CreateObject("Scripting.FileSystemObject")  ‘Object Creation for File system 
   Set folder = fso.GetFolder(Left(TracePath,len(TracePath)-1)) ‘Object Creation for Folder Access 
   Set files = folder.Files                                     ‘Object Creation For File Access

i=0

 For each fileIdx In files                     ‘Loop For Accessing the Files in the Source Folder
 FName = fileIdx.Name
              if right(FName ,4) = ".trc" then  ‘Checking the file Extension of the Trace file
                 Redim Preserve allFiles(i) 
                 Redim Preserve allTimeStamps(i)
                 allFiles(i)=fileIdx.Name       ‘Storing a Filename in a Array
                 allTimeStamps(i)=fileIdx.DateLastModified ‘Storing the Datemodified value of file
                      i=i+1
              end if
 Next

               'Now sort as per Modified TimeStamp  
 for i =  lbound(allTimeStamps) to ubound(allTimeStamps)
       for j =  lbound(allTimeStamps) to ubound(allTimeStamps)
              if allTimeStamps(i)<allTimeStamps(j) then
                     tt=allTimeStamps(i)
                     allTimeStamps(i)=allTimeStamps(j)
                      allTimeStamps(j)=tt
                      tt=allFiles(i)
                     allFiles(i)=allFiles(j)
                     allFiles(j)=tt
              end if
       next
 next

for i =  lbound(allFiles) to ubound(allFiles) -1        ' -1 so that we leave the latest file
       fso.movefile TracePath&allFiles(i) ,"P:\Audit\"  ‘Move the trace to Destination Path
Next

set fso = Nothing     ‘Clearing the Created Objects
set folder = Nothing
Set files = Nothing


Finally you can create a Step for Success and failure status mail for Mail Alert

Thursday, May 10, 2012

SQL 2005 - Finding and Listing ALL Procedures, Functions, and Views in SQL Server 2005

Below is the most basic coding to find out ALL of the Stored Procedures that exist within SQL Server 2005.

USE [your_database_name_here];
GO
SELECT * FROM sys.all_objects
WHERE ([type] = 'P' OR [type] = 'FN' OR [type] = 'V')
ORDER BY [name];
GO

This coding is based on filter by the object "type". Use the following table to determine the type of object you want returned, and then adjust the WHERE clause to only return those type(s) you wish to be returned. This listing only lists views, functions, and procedures. There are other types which you can also filter, be sure to review BOL for further information on the types.

Type
 Type Of Object Returned
FN
SQL Scalar Function
IF
Inline Table Valued Function
P
SQL Stored Procedure
PC
CLR Stored Procedure
TF
SQL Table Valued Function
V
View
X
Extended Stored Procedure

User-Defined Stored Procedures

Now, one other field that is worthwhile to filter by is the "is_ms_shipped" field. This, obviously, determines if the SP was originally shipped by Microsoft. If the value of the field is 0 then it was NOT shipped by MS; if the value is 1 then it WAS shipped by MS. Simple enough. If you want to use it in conjunction with the above TSQL statement you will put in "AND [is_ms_shipped] = 0" to find SPs that were NOT created by MS, and most likely created by yourself or someone else with access to your database. If you ONLY want MS provided SPs then change the value from 0 to 1.
Here is a TSQL coding example of how to obtain only User-Defined SPs (using the previously mentioned "is_ms_shipped" field to obtain the listing). Note: This listing will definitely vary depending on what SPs you have installed. If you received no results then this indicates the database you are running your query on does not contain any SPs that were not created by MS...Try another database that you know you have created an SP for, or create an SP for your database and re-run the query.

USE [your_database_name_here];
SELECT * FROM sys.all_objects
WHERE ([type] = 'P' OR [type] = 'X' OR [type] = 'PC')
AND [is_ms_shipped] = 0
ORDER BY [name];
GO

Thursday, April 19, 2012

SQL DBA - Msg 8914, Level 16, State 1, Line 1 Incorrect PFS free space information

Errors :-  

When u Run DBCC CHECKDB you will get a Error like this :-
 
Msg 8914, Level 16, State 1, Line 1
Incorrect PFS free space information for page (1:278) in object ID 1047674780, index ID 0, partition ID 72057594052018176, alloc unit ID 72057594065125376 (type LOB data). Expected value   0_PCT_FULL, actual value 100_PCT_FULL.

There are 701 rows in 359 pages for object "XXXxxxXXXxxxXXX".
CHECKDB found 0 allocation errors and 6 consistency errors in table 'XXXxxxXXXxxxXXX' (object ID 1047674780).

Solution For this Error :-
             1. Check which Table is corrupted using.
  DBCC Checktable ('Your_Table_Name’).
2.Run this Query to Change DB into Single User Mode.
  ALTER DATABASE corrupted_db SET SINGLE_USER WITH ROLLBACK IMMEDIATE

3.Run this Query to Recover the Table/DB. 
 DBCC CheckTable ('corrupted_table', REPAIR_ALLOW_DATA_LOSS)

4.Once this Execution Completed Sql returns “Errors are Corrected” .

5.Run this Query to Change the DB into MultiUser Mode.
 ALTER DATABASE corrupted_db SET MULTI_USER

Here are the technical details of the problem :

The issue was that when minimal logging for LOBs was used (under the SIMPLE recovery model, during BULK INSERT/BCP/Large insert with TABLOCK), extents are being pre-allocated and the pages were being marked 100% full in the PFS page when the pages were allocated. The idea was that all pages eventually will be filled up with LOB data, and by marking them full during allocation we avoid an extra update to the PFS pages when the data is actually put on the page.

Suppose now that 64 pages are pre-allocated, and only 40 or so pages are used and have rows on them. When the transaction commits, the Storage Engine is supposed to deallocate the 24 extra pages that were pre-allocated, and marked 100% full, even though they don’t have any rows on them yet. There was a bug where in a certain case the deallocation wouldn't happen, so you end up with empty pages that have a PFS state of 100%, but don’t have any rows on them.

In general, even though this is a bug in the code, functionality wise, there is nothing wrong with the database, besides a number of additional pages that are empty and allocated to the LOB tree, so as long as the message tells you that the page is supposed to be empty, but is actually marked 100%, nothing can really go wrong with that page. Unfortunately, DBCC will keep reporting these errors.

Although I haven't tried this, my guess is that you can get rid of the empty LOB pages using ALTER INDEX ... REORGANIZE WITH (LOB_COMPACTION = ON). So, if you see some of these errors with no other errors, you may have hit this bug and have nothing really to worry about.