Siddharth sood

noida, INDIA


Joined May 26th 2008

Number of Posts:
99

Number of Comments:
0

Karma:
7



Tags & Posts

Bookmark Tags



Popular Tags

Popular Posts

Blogs

Siddharth sood's Blogs

35 Vote(s)
0 Comment(s)
1 Post(s)
75 Vote(s)
0 Comment(s)
2 Post(s)
35 Vote(s)
0 Comment(s)
1 Post(s)
48 Vote(s)
0 Comment(s)
1 Post(s)
27 Vote(s)
0 Comment(s)
1 Post(s)
67 Vote(s)
0 Comment(s)
2 Post(s)
146 Vote(s)
0 Comment(s)
4 Post(s)
193 Vote(s)
2 Comment(s)
5 Post(s)
3909 Vote(s)
13 Comment(s)
79 Post(s)
24 Vote(s)
0 Comment(s)
1 Post(s)
23 Vote(s)
0 Comment(s)
1 Post(s)

I mentor these bloggers

Learn more about the Orble Mentoring Program.


I do not mentor any bloggers.

Friends

I have no friends :(

Recent Posts

Database Mail and SQL Agent Mail setup by using a script



Problem
I was in the middle of upgrading many servers to SQL Server 2005 and SQL Server 2008. As I was setting up Database Mail and the SQL Server Agent Alert System I wanted to create a script that I could use to do this instead of having to do this manually through the GUI. In this tip I provide a script with a few parameters that need to be setup to configure and turn on both of these features.

Solution
SQL 2005 and later versions have this new option to use SMTP to send email from SQL Server and this can be setup using the GUI or by using scripts. In this tip, I go through the steps to set this up by only using scripts.


----------------------------- ----------------------------- ----------------------

The following breaks down the overall script into four sections, so I can explain what each section does. The entire script can be download from here which I encourage you to use instead of having to piece the sections together.



Section 1 - Declare and Set Values

Before you run the script, you will need to fill out some information for your environment. The four values that need to be set are:

@SMTPServer - You will need to get SMTP server that you want to use to send email out.
@AdminEmail - After setup, the script will send test email to this email address
@DomainName - This will be part of SQL Server Email Name
@replyToEmail - this is how you will see for reply to email when you get the email.

use master
DECLARE @SMTPServer VARCHAR(100)
DECLARE @AdminEmail VARCHAR(100)
DECLARE @DomainName VARCHAR(100)
DECLARE @replyToEmail VARCHAR(100)

SET @SMTPServer = 'smtp.mydomain.com'
SET @AdminEmail = 'klee@mydomain.com'
SET @DomainName = '@mydomain.com'
SET @replyToEmail = 'sqlserver@mydomain.com'




----------------------------- ----------------------------- ----------------------

Section 2 - Change Global Configuration Settings

In order to setup Database Mail and SQL Agent mail, you will need to turn on two global configuration settings.

exec sp_configure 'show advanced options', 1
exec sp_configure 'Database Mail XPs', 1
exec sp_configure 'Agent XPs',1
RECONFIGURE WITH OVERRIDE



----------------------------- ----------------------------- ----------------------

Section 3 - Database Mail Configuration

This will setup database mail. It does not require the SQL Server service to be restarted. At the end of the script, it will send a Test Mail.

The email address that will be configured for Database Mail is based on the server name. So if your server name is "ProdServer1" and your domain is "MyDomain.com" the email address that this script creates is "ProdServer1@MyDomain.com". If you want something different you will need to modify the script.

Also, this uses "anonymous authentication" for the mail server. If you want to provide other parameters take a look at these system stored procedures; sysmail_add_account_sp, sysmail_add_profile_sp, sysmail_add_profileaccount_sp and sysmail_add_principalprofile_ sp.

declare @servername varchar(100)
declare @email_address varchar(100)
declare @display_name varchar(100)
declare @testmsg varchar(100)
set @servername = replace(@@servername,'\','_')
set @email_address = @servername @DomainName
set @display_name = 'MSSQL - ' @servername
set @testmsg = 'Test from ' @servername
IF EXISTS(SELECT * from msdb.dbo.sysmail_profile)
PRINT 'DB mail already configured'
ELSE
BEGIN
--Create database mail account.
exec msdb.dbo.sysmail_add_account_ sp
@Account_name = 'SQLMail Account'
, @description = 'Mail account for use by all database users.'
, @email_address = @email_address
, @replyto_address = @replyToEmail
, @display_name = @display_name
, @mailserver_name = @SMTPServer
--Create global mail profile.
exec msdb.dbo.sysmail_add_profile_ sp
@profile_name = 'SQLMail Profile'
, @description = 'Mail profile setup for email from this SQL Server'
--Add the account to the profile.
exec msdb.dbo.sysmail_add_profilea ccount_sp
@profile_name = 'SQLMail Profile'
, @Account_name = 'SQLMail Account'
, @sequence_number=1
--grant access to the profile to all users in the msdb database
use msdb
exec msdb.dbo.sysmail_add_principa lprofile_sp
@profile_name = 'SQLMail Profile'
, @principal_name = 'public'
, @is_default = 1
END
--send a test message.
exec msdb..sp_send_dbmail
@profile_name = 'SQLMail Profile',
@recipients = @AdminEmail,
@subject = @testmsg,
@body = @testmsg

EXEC msdb.dbo.sysmail_help_profile _sp





----------------------------- ----------------------------- ----------------------

Section 4 - SQL Agent Mail Configuration

Once Database Mail is setup, you now can enable SQL Agent notifications. To take affect, this may require the SQL Agent Service to be restarted.

In order to send out email from SQL Agent you need to configure the Alert System. The script below will do this. In uses the extended stored procedure "xp_instance_regwrite" to write two values to the registry. The first setting just tells the SQL Agent Alert System to use Database Mail as the email option and the second setting tells the SQL Agent Alert System which mail profile to set. The value "SQLMail Profile" was the name that was given in Section 3.

-- Enabling SQL Agent notification
USE [msdb]
EXEC msdb.dbo.sp_set_sqlagent_prop erties
@email_save_in_sent_folder=1

EXEC master.dbo.xp_instance_regwri te
N'HKEY_LOCAL_MACHINE'
, N'SOFTWARE\Microsoft\MSSQLSer ver\SQLServerAgent'
, N'UseDatabaseMail'
, N'REG_DWORD'
, 1

EXEC master.dbo.xp_instance_regwri te
N'HKEY_LOCAL_MACHINE'
, N'SOFTWARE\Microsoft\MSSQLSer ver\SQLServerAgent'
, N'DatabaseMailProfile'
, N'REG_SZ'
, N'SQLMail Profile'




----------------------------- ----------------------------- ----------------------

There are many things that you can automate by scripting when it comes to SQL Server related tasks. This saves a lot of time if you need to do this over and over again as well as to ensure things are kept consistent.

14
Vote
   


SQL SERVER Database Mail Cleanup Procedures

Problem
I have been using Database Mail for a while and it is causing a lot of growth in my msdb database. What is the best way to delete the excess data stored in the msdb due to Database Mail?

Solution
There are two system stored procedures you can take advantage of in order to clean up Database Mail messages, attachments and log entries stored in the msdb database. These two system stored procedures are sysmail_delete_mailitems_sp and sysmail_delete_log_sp.

You can execute the sysmail_delete_mailitems_sp stored procedure located in the msdb database to:

delete all mail messages
delete messages older than a given date
delete messages with a given status or
delete messages older than a given date with a certain status.

The complete syntax is shown below. If you execute the sysmail_delete_mailitems_sp stored procedure without any parameters, all mail messages will be deleted.

sysmail_delete_mailitems_sp
[ [ @sent_before = ] 'sent_before' ] -- '1/1/2009'
[ , [ @sent_status = ] 'sent_status' ] -- sent, unsent, retrying, failed



You can execute the sysmail_delete_log_sp stored procedure located in the msdb database to:

delete all log entries
delete all log entries prior to a given date
delete log entries for a certain event type or
delete delete log entries prior to a given date for a certain event type.

The complete syntax is shown below. If you execute the sysmail_delete_log_sp stored procedure without any parameters, all log entries will be deleted.

sysmail_delete_log_sp
[ [ @logged_before = ] 'logged_before' ] --'1/1/2009'
[, [ @event_type = ] 'event_type' ] --success, warning, error, informational



You should come up with a retention policy and schedule a job to run periodically to clean up the Database Mail history. For example, the following script will delete all mail entries older than thirty days.

DECLARE @DeleteBeforeDate DateTime = (Select DATEADD(d,-30, GETDATE()))
EXEC sysmail_delete_mailitems_sp @sent_before = @DeleteBeforeDate
EXEC sysmail_delete_log_sp @logged_before = @DeleteBeforeDate



Note: the syntax above in the first line is new for SQL 2008 where you can declare and set a value at the same time. For SQL 2005 you would need to do this with two lines, first the DECLARE and then setting the value as follows:

DECLARE @DeleteBeforeDate DateTime
SELECT @DeleteBeforeDate = DATEADD(d,-30, GETDATE())
EXEC sysmail_delete_mailitems_sp @sent_before = @DeleteBeforeDate
EXEC sysmail_delete_log_sp @logged_before = @DeleteBeforeDate






14
Vote
   


Different ways to execute a SQL Agent job


Problem:
Every database person might have come across the situation of maintenance tasks such as backing up of databases, re-indexing tables and other such tasks. We often schedule jobs for such tasks, so that they execute as per the set schedule. But there is sometimes the need for these tasks to be executed “On Demand”. This tip shows various ways of executing such tasks on demand by any user regardless of whether the person is technical or not.

Solution
Let’s say I have a job called “BACKUPTEST” which backups the test databases. I want to be able to execute the job “On Demand”, so whenever anyone needs to do the backup this can be done. In this article I will show you how you can execute such Jobs easily through various ways.

In this tip we will look at these four methods:

SQL Server Management Studio
T-SQL commands
DMO (Distributed Management Objects)
OSQL

Also, this tip assumes that the jobs have already been setup.


----------------------------- ----------------------------- ----------------------

(1) - SQL Server Management Studio

The first way that most people are probably aware of is to use SQL Server Management Studio.

SQL Server Agent is the job scheduling tool for SQL Server.

To execute a job on demand using the GUI, open the SQL Server Agent tree, expand Jobs, select the job you want to run, right click on that job and click ‘Start Job’ and the job will execute.






----------------------------- ----------------------------- ----------------------

(2) -T-SQL commands

The second way is through a T-SQL statement using the 'sp_start_job' stored procedure which instructs SQL Server Agent to execute a job immediately. It is a stored procedure in the 'msdb' database.

The syntax for the sp_start_job stored procedure is:

sp_start_job
[@job_name] or [@job_id ]
[,@error_flag ]
[,@server_name]
[,@step_name ]
[,@output_flag ]



Arguments:

[@job_name] | [@job_id ] Is the name of the job to start. Either job_id or job_name must be specified, but both cannot be specified. job_name is sysname, with a default of NULL.

[@error_flag =] error_flag Reserved.

[@server_name =] 'server_name' Is the target server on which to start the job. server_name is nvarchar(30), with a default of NULL. server_name must be one of the target servers to which the job is currently targeted.

[@step_name =] 'step_name' Is the name of the step at which to begin execution of the job. Applies only to local jobs. step_name is sysname, with a default of NULL

[@output_flag =] output_flag Reserved.

When a job run it will have one of two return codes:

0 (success)
1 (failure)

To run the job ‘BACKUPTEST’ it can be executed by a single T-SQL statement: such as:

EXEC msdb.dbo.sp_start_job 'BACKUPTEST'




----------------------------- ----------------------------- ----------------------

(3) -DMO (Distributed Management Objects)





Another way of executing the job is through a VBS script using Distributed Management Objects (DMO).

Here is the basic script syntax.

On Error Goto 0: Main()
Sub Main()
Set objSQL = CreateObject("SQLDMO.SQLServe r")
' Leave as trusted connection
objSQL.LoginSecure = True
' Change to match the name of your SQL server
objSQL.Connect "Enter Server Name Here"
Set objJob = objSQL.JobServer
For each job in objJob.Jobs
if instr(1,job.Name,"Enter Job Name Here") > 0 then
msgbox job.Name
job.Start
msgbox "Job Started"
end if
Next
End Sub



Here is sample executing the "BACKUPTEST" job on server "SQLTEST1". This uses NT authentication to run this script.

On Error Goto 0: Main()
Sub Main()
Set objSQL = CreateObject("SQLDMO.SQLServe r")
' Leave as trusted connection
objSQL.LoginSecure = True
' Change to match the name of your SQL server
objSQL.Connect "SQLTEST1"
Set objJob = objSQL.JobServer
For each job in objJob.Jobs
if instr(1,job.Name,"BACKUPTEST") > 0 then
msgbox job.Name
job.Start
msgbox "Job Started"
end if
Next
End Sub



This code would then be saved in a file and named something like "RunJob.vbs". You can then double click on the file to execute it or run the code from a command line.


----------------------------- ----------------------------- ----------------------

(4) - Using osql utility

Lastly, we can start the job using osql commands.

The osql utility allows you to enter T-SQL statements, system procedures, and script files.

Here is the basic script syntax.

osql -S "Enter Server Name Here" -E -Q"exec msdb.dbo.sp_start_job 'Enter Job Name Here'"



Open a command prompt and execute the below osql command in it:, replacing your server name and job name.

osql -S "SQLTEST1" -E -Q"exec msdb.dbo.sp_start_job 'BACKUPTEST'"



The next step is to make a batch file which can be run over and over again.

Open notepad and type the commands as follow:

ECHO Executing job
ECHO.
pause
osql -s "MYPC\SQL" -E -Q"exec msdb.dbo.sp_start_job 'BACKUPTEST' "

ECHO job execution completed
pause
CLS
EXIT





Save the file as “job.bat”.


The batch is now ready for use. Just double click on it and it will do the maintenance work without having any knowledge of SQL Server.


----------------------------- ----------------------------- ----------------------


Permissions

You might have noticed in all the four solutions the msdb stored procedure ‘sp_start_job’ is used in one way or another.

By default, members of the sysadmin fixed server role can execute this stored procedure.

Other users must be granted one of the following SQL Server Agent fixed database roles in the msdb database:

SQLAgentUserRole
SQLAgentReaderRole
SQLAgentOperatorRole
Members of SQLAgentUserRole and SQLAgentReaderRole can only start jobs that they own.

Members of SQLAgentOperatorRole can start all local jobs including those that are owned by other users.

Members of sysadmin can start all local and multiserver jobs.



For details about the permissions of these roles, see SQL Server Agent Fixed Database Roles. and SQL Server Agent Fixed Database Roles



15
Vote
   


When was the last time your SQL Server database was restored


[ Click here to read more ]
14
Vote
   


Handling workloads on SQL Server 2008 with Resource Governor


[ Click here to read more ]
27
Vote
   


Collecting performance counters and using SQL Server to analyze the data


[ Click here to read more ]
16
Vote
   


SQL Server UDF to convert integer date to datetime format

Problem


[ Click here to read more ]
17
Vote
   


Handling cross database joins that have different collations (SQL Server)

Problem


[ Click here to read more ]
19
Vote
   


Server level permissions for SQL Server 2005 and 2008

Problem


[ Click here to read more ]
16
Vote
   


Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32)

Problem


[ Click here to read more ]
43
Vote
   


 

Recent Comments

I've not commented on anything yet :(