Showing posts with label dba. Show all posts
Showing posts with label dba. Show all posts

Monday, 25 May 2015

SQL Server High Availability - Manual Failover by serverku

Availability As we have seen SQL Server High Availability configuration and listener since same, I would like to go ahead for manual failover test in SQL Server 2012. So I would suggest to go through related previous posts.
  1. Configure Listener for high availability in SQL Server
  2. Implement High Availability in SQL Server - How to
Moving to test manual failover of SQL Server High Availability and following are the steps. Here Server 2 is a primary replica and Server1 is a secondary replica. Now we have to switch over the primary role from Server2 to Server1.

Step 1 : Connect primary replica availability group. Go to Availability Group and right clink on that and click on Failover.


Step 2 :Select instance, which you want to make a primary replica as shown in the image.


Step 3 : Connect SQL server instance, which you selected in earlier steps.


Step 4 : Click on Next and You can see the current primary replica and new primary replica.


Step 5 : Finally success on next step.


Step 6 : Last step to confirm primary replica, so connect with listener name and confirm as shown in the image.


This is just a manual failover test of Availability Group and hope you enjoyed it. In the next post we will see automated failover of Availability Group.

Friday, 8 May 2015

Configure Listener for high availability in SQL Server 2012 by serverku

A week ago I posted for high availability implementation in SQL Server 2012. I would like to read the earlier post and continue that post with and it’s configure a listener for availability group. So let us follow the steps.

Step 1 :  Connect primary server instance of availability group and go to AlwaysOn High Availability –> Availability Groups—> Availability Group Listeners –> Add Listener


Step 2 :  Assign Listener DNS Name, Port and Network Mode which should be DHCP or statistic IP.


Step 3 : We are done and now it ‘s time to connect and confirm SQL Server primary instance.


It should connect SQL Server primary instance, even a case of automatic or manual failover of instance involved in Availability Groups. So whenever a failover or primary server failure happened, we do not need to changed data source\connection string of application or wherever used. Hope you may like it.

Thursday, 7 May 2015

Implement High Availability in SQL Server - How to by serverku

A week ago I wrote for the replication, how to add articles in replication, how to add filtered articles in replication. Today I would like to write for high availability implementation in SQL server. It is the best option to replace other disaster plans like mirroring, replication and clustering based on need. So let us elaborate it with steps. We will go ahead with an example of SQL Server 2012 enterprise.

1.  Install and configure Windows Failover Cluster’. Go to Server Manager –>Features—>Add features.


2. Select ‘Failover Clustering’ from feature and add it.


3. After Windows Failover Cluster installed Create a Cluster. Go to Failover Cluster Manager –> Create Cluster.


4. Add Servers which need to participate in cluster.


5. Select an option to run validation tests for added servers.


6. Select an option either you wan to run all test or selected tests.


7. Specify a Cluster name and add IP address reserved for windows cluster name object.


8.  Open Failover Cluster Manager and confirm all server added in Nodes.


9. Install SQL Server SQL Server 2012 standalone in all servers and make sure ‘AlwaysOn Availability Groups’ enabled for SQL server instances.


10.  Here we will have a ‘Server1’ as a Primary, ‘Server2’ and ‘Server3’ act as a Secondary. So let us create a sample database in primary server.



11. Make sure the location of databases should be same to all secondary servers and databases have a full recovery model.

12.  Connect primary SQL server instance, go to AlwaysOn High Availability —> New Availability Group Wizard.


13. Specify a AG  name.


14.  Select databases which you would like to participate in AG. Make sure database full backup must be done, also it can be seen in status there.



15. Add ‘Server2’ and ‘Server3’ as a replica and set Server1 and Server2 for Automatic Failover. Make Readable setting for replicas as per need.


16.  Make sure 1433 (or whatever port of instances) and 5022 should be open in the firewall if the firewall is turned on.

17.  Set option of backup preferences and priority where you would like to perform it.


18.  Make one shared folder for full backup of databases which must be accessible to all secondary servers to restore it there.


19. Expand AlwaysOn High Availability—> Availability groups—>Availability Replicas where you can all participated servers in AG.


I will write next some more about it. Hope you enjoy AG. Have a nice day!

Wednesday, 6 May 2015

Script to get undistributed commands in replication - SQL Server by serverku

This post is about replication, you may read some earlier posts for the same. I would like you to go through the same with below links,
Configuration Replication failure and retry alert-SQL Server
Script to get replication latency and alert in SQL Server
The row was not found at the Subscriber when applying the replicated command - Alternate workaround
Copy nonclustered indexes to subscriber while generating snapshot - SQL Server Replication
Hope you enjoyed above posts and now going ahead to share information about the past of undistributed commands in transaction replication. Let me share a script here which runs against a distribution database on distributor server.
USE DISTRIBUTION
GO
EXECUTE sp_replmonitorsubscriptionpendingcmds
@publisher ='publisher', -- Put publisher server name here
@publisher_db = 'publisher_db', -- Put publisher database name here
@publication ='publication', -- Put publication name here
@subscriber ='subscriber', -- Put subscriber server name here
@subscriber_db ='subscriber_db', -- Put subscriber database name here
@subscription_type ='1' -- 0 = push and 1 = pull
Above execution output is as follows,


This returns pending undistributed commands and estimated processing time for same for particular subscriber and some other parameters passed through the script. This is a same information which returns from subscriber details in the replication monitor as below,


Hope you liked it and stay tuned for more. I will come with another post which have different script to get the same information.

Another way to list out running scheduled jobs - SQL Server by serverku

We have been discussing the way to get scheduled jobs which are executing. Also wanted to tell you that this way is just similar to an earlier post with the same subject, but this an another alternate way. Please read my earlier relative posts for the same. You may aware of the dbo. sp_help_job which also help us they get the same information which you may read my one of the recent post.

Here I am sharing one more way to get the same information, where need to use sp_get_composite_job_info system object from msdb database and pass @execution_status parameter and value should be 1 for executing state.
USE msdb
GO

EXEC dbo.sp_get_composite_job_info @execution_status=1;
This will output all jobs which are currently executing. But when you run EXEC msdb.dbo.sp_get_composite_job_info without any parameter, it will give all the jobs and status as well. And the state values are following,
0 = Not idle or suspended,
1 = Executing,
2 = Waiting For Thread,
3 = Between Retries,
4 = Idle,
5 = Suspended,
6 = WaitingForStepToFinish,
7 = PerformingCompletionActions
You can pass any parameter values to get the jobs having that state. We all know about the query to get enabled\disabled scheduled jobs using db.sysjobs system table and having enabled = 1, but the same information we can know using msdb.dbo.sp_get_composite_job_info as following,
USE msdb
GO

-- Enabled jobs
EXEC dbo.sp_get_composite_job_info @enabled = 1;

-- Disabled jobs
EXEC dbo.sp_get_composite_job_info @enabled = 0;
There are some other parameters which also can be used with this object like job_id, job_type etc. You may aware of this sp and may be used. Please suggest any other way using this object.

Tuesday, 5 May 2015

Script to get failed scheduled jobs in SQL Server by serverku

As we were talking about to get start time and end time of schedule jobs a week before, We are going to use same information, but it will be with the scheduled jobs having last status is filed for any steps. So I request to go through that post. Also visit post to get running jobs and the way to get it. The DBA needs to know the scheduled job status on routine duty.

Some of the jobs having schedule occurrence one time and some of them have recursive occurrence. Need to list out those jobs having last status is Fail. It may be possible some jobs have multiple steps and among them some fail, so those jobs should be coming into the list. And have to exclude running jobs, even if are failed earlier.

Here I am sharing one script which will alert us with those jobs which failed today and have following criteria,
  1. List out failed jobs for today
  2. List out jobs which have a last status as fail
  3. Need Job Name, Start Time and End Time too
  4. Excluding running jobs
USE msdb
GO

-- Creating a temp table
CREATE TABLE #RunningJobs
(
job_id UNIQUEIDENTIFIER NOT NULL,
last_run_date INT NOT NULL,
last_run_time INT NOT NULL,
next_run_date INT NOT NULL,
next_run_time INT NOT NULL,
next_run_schedule_id INT NOT NULL,
requested_to_run INT NOT NULL,
request_source INT NOT NULL,
request_source_id sysname COLLATE database_default NULL,
running INT NOT NULL,
current_step INT NOT NULL,
current_retry_attempt INT NOT NULL,
job_state INT NOT NULL
)

-- Insert the running jobs in this temp table
INSERT INTO #RunningJobs
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,'sa'

SELECT
SERVERPROPERTY ('servername') as ServerName,
res.name as JobName,
-- converting run_date and run_time to proper date time format for Start Time
CAST(
CONVERT(CHAR(8), run_date, 112) + ' ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), run_time), 6), 5, 0, ':'), 3, 0, ':')
AS DateTime) AS StartedAt,
-- converting run_date,run_time and run_duration to proper date time format for Finish Time
(CONVERT (VARCHAR,
(DATEADD(ss,
(CASE LEN(run_duration)
WHEN 1
THEN run_duration
WHEN 2
THEN run_duration
WHEN 3
THEN (CAST(Left(right(run_duration,3),1) as int)*60)
+ (right(run_duration,2))
WHEN 4
THEN (CAST(Left(right(run_duration,4),2) AS int)*60)
+ (right(run_duration,2))
WHEN 5
THEN (CAST(Left(right(run_duration,5),1) AS int)*3600)
+ (CAST(Left(right(run_duration,4),2) AS int)*60)
+ right(run_duration,2)
WHEN 6
THEN (CAST(Left(right(run_duration,6),2) AS int)*3600)
+ (CAST(Left(right(run_duration,4),2) AS int)*60)
+ right(run_duration,2)
END ),
CAST(
CONVERT(CHAR(8), run_date, 112) + ' ' +
STUFF(STUFF(RIGHT('000000' + CONVERT(VARCHAR(8), run_time), 6), 5, 0, ':'), 3, 0, ':')
AS DateTime)))
,120)) AS FailedAt
FROM (SELECT Row_number()
OVER(
partition BY sj.name
ORDER BY run_time DESC) AS rnk,
sj.job_id,
sj.name,
run_date,
run_time,
run_duration,
run_status
FROM msdb.dbo.sysjobhistory sjh WITH (nolock)
INNER JOIN msdb.dbo.sysjobs sj WITH (nolock)
ON sjh.job_id = sj.job_id
WHERE sjh.step_id <> 0
-- considering for today only
AND run_date = CONVERT(VARCHAR(8), Getdate(), 112)
) res
WHERE
-- Failed status
res.run_status = 0
-- Lastly failed
AND res.rnk = 1
-- excluding running jobs
AND NOT EXISTS (SELECT rj.job_id
FROM #runningjobs rj
WHERE rj.job_id = res.job_id
AND rj.running = 1)
-- Droping table
DROP TABLE #RunningJobs
We can also set an alert for those failed jobs in email. I would like you to share your thoughts and the way you are using to get failed job details.

Script to get transactional replication errors for all subscriptions - SQL Server by serverku

Earlier post had same title just with a little bit difference of giving subscribers and all subscribers, so sharing a script which you can watch transactional replication error for all subscribers and get an alert at the time of error raise. Before going ahead with this post I would like you to read my earlier post and share your thoughts there.
So diverting on this post and again sharing script to get the same information, but it for all subscribers, you can also use the parameter of subscriber in where condition to apply filters.
Use distribution
GO
SELECT ma.publisher_db,
ma.publication,
ma.subscriber_db,
msre.time,
msre.error_text
FROM msrepl_errors msre
INNER JOIN msdistribution_history msh
ON ( msre.id = msh.error_id )
INNER JOIN msdistribution_agents ma
ON ( ma.id = msh.agent_id )
ORDER BY msre.time DESC
This is just a script which I want to present here. Now how can watch and keep attention when such any error occurs for transactional replication error in last 5 minutes and get an alert for the same with following script which can be scheduled every 5 minutes or whatever frequency as per filter applied of error time in query and run against a distribution database on distributor server,
USE distribution 
GO

DECLARE @body VARCHAR(max),
@subject VARCHAR(100),
@Publication VARCHAR(50),
@SubscriberDB VARCHAR(50),
@ErrorText VATCHAR(max)

SELECT @Publication = ma.publication,
@SubscriberDB = ma.subscriber_db,
@ErrorText = msre.error_text
FROM msrepl_errors msre
INNER JOIN msdistribution_history msh
ON ( msre.id = msh.error_id )
INNER JOIN msdistribution_agents ma
ON ( ma.id = msh.agent_id )
WHERE msre.time >= Dateadd(minute, -5, Getdate())
-- Capturing for last 5 minutes
ORDER BY msre.time DESC

SET @subject = 'Error captured for ' + @SubscriberDB
+ ' subscriber database of ' + @Publication
+ ' publication'
SET @body = @ErrorText

-- Sending an email
IF ( @subject IS NOT NULL )
BEGIN
EXEC msdb.dbo.Sp_send_dbmail
@recipients = 'prajapatipareshm@gmail.com',
@subject = @subject,
@body = @body,
@profile_name = '<Profile name>',
@body_format = 'HTML';
END

Have you scheduled any such script to get an alert and watch for any transaction replication error? Your ideas and thoughts are most welcome.

Monday, 4 May 2015

Configuration Replication failure and retry alert - SQL Server by serverku

As I wrote about replication latency from publisher to distributor and distributor to subscriber for replication and an alert for replication latency, same as we need to have an alert in case of replication failure. I would like to review some of my earlier posts about replication before moving to this post which you may like,
  1. Skip Log Reader error in SQL Server replication - How to
  2. Review of some replication issues and workaround - SQL Server
  3. Could not find the Distributor or the distribution database for the local server-Error while posts a tracer token in Replication
Let the discussion to move ahead and check as how can we set up an alert for in case of replication failure. So going with steps,

1. Create a job which having static code to fire an email as follows and do not need to schedule it,
DECLARE @Subject varchar(50), @body varchar(200)
SET @Subject = 'Replication Alert (Agent Failure)'
SET @body = 'Replication Alert (Agent Failure).<BR />Check the status of agent from replication monitor.'

EXEC msdb.dbo.sp_send_dbmail
@recipients = 'prajapatipareshm@gmail.com',
@subject = @Subject,
@body = @body,
@profile_name = '<Profile Name>',
@body_format = 'HTML';
2. Go to Replication monitor from Replication tab under SQL Server instance.


3. Select the Publication for which you want to receive an alert for failure and move to Warning tab as follows,


4. Go Configure alert and select “Replication : agent failure” as mentioned in below image,


5. For agent property, click on configure button  –> Response tab and select the job which we created earlier in step 1 in Execute job check box,


This is the just steps to configure an alert for replication agent failure. We can also add a notification alert to job operators also, so whenever the replication agent fails, this configuration runs the job and it will fire an email. We can set up the same configuration for replication agent retry too.

Script to get replication latency and alert in SQL Server by serverku

Recently I had posted for one issue I faced for replication trace token, Could not find the Distributor or the distribution database for the local server. Hope you read and liked it. Today I am writing for replication latency and its alert and I am using one script to post a tracer token which I used same in an earlier post where you can see the script there and details for same. So move on the topic here as how can we get replication latency information and alert for same. Putting in steps,

1. Post tracer tokens : Schedule a script to post a tracer tokens frequently, says 5 minutes, which posts a trace token into the transaction log at the Publisher and begins the process of tracking latency statistics and run this script at publisher,
USE publisherdb 
GO

DECLARE @out_tracer_token_id INT

EXEC sys.Sp_posttracertoken
@publication = N'<Publication Name>', -- Put Publication name here
@tracer_token_id=@out_tracer_token_id out

SELECT @out_tracer_token_id
 2. Script : After scheduling above scripts every 5 minutes, which will put latency history in MStracer_history system table in distribution database, following script use to get details for the latency from publisher to distributor and distributor to subscriber which belongs to distribution database,
USE distribution 
GO

SELECT publisher_db AS
[PublisherDB]
,
publication
AS [Publication],
name AS
[Subscriber],
subscriber_db AS
[SubscriberDB],
RIGHT('0' + Cast([timetosubscriber]/3600 AS VARCHAR(3)), 2)
+ ':'
+ RIGHT('0' + Cast(([timetosubscriber] % 3600) / 60 AS VARCHAR(2)), 2)
+ ':'
+ RIGHT('0' + Cast(([timetosubscriber] % 60) AS VARCHAR(2)), 2) AS
[DistToSubLatency],
RIGHT('0' + Cast([timetopublisher]/3600 AS VARCHAR(3)), 2)
+ ':'
+ RIGHT('0' + Cast(([timetopublisher] % 3600) / 60 AS VARCHAR(2)), 2)
+ ':'
+ RIGHT('0' + Cast(([timetopublisher] % 60) AS VARCHAR(2)), 2) AS
[PubToDistLatency],
RIGHT('0' + Cast([totaltime]/3600 AS VARCHAR(3)), 2)
+ ':'
+ RIGHT('0' + Cast(([totaltime] % 3600) / 60 AS VARCHAR(2)), 2)
+ ':'
+ RIGHT('0' + Cast(([totaltime] % 60) AS VARCHAR(2)), 2) AS
[TotalLatency]
FROM (SELECT DISTINCT msda.publisher_db,
syss.name,
msda.subscriber_db,
msda.publication,
publisher_commit,
distributor_commit,
Datediff(ss, publisher_commit, distributor_commit) AS
[TimeToPublisher],
subscriber_commit,
Datediff(ss, distributor_commit, subscriber_commit) AS
[TimeToSubscriber],
Datediff(ss, publisher_commit, distributor_commit)
+ Datediff(ss, distributor_commit, subscriber_commit) AS
[TotalTime]
FROM mstracer_history msth
INNER JOIN msdistribution_agents msda
ON msth.agent_id = msda.id
INNER JOIN sys.servers syss
ON msda.subscriber_id = syss.server_id
INNER JOIN mstracer_tokens
ON msth.parent_tracer_id = mstracer_tokens.tracer_id
WHERE subscriber_commit > Dateadd(mi, -5, Getdate())) res
ORDER BY [totaltime] DESC
3. Alert : As we have seen a script to get the latency for replication, herewith I am sharing a script to get alerts for highest latency, In script logic is implies to send an alert only when a publisher to distributor or distributor to subscriber latency exceed 1 minute. You can schedule this script to every 5 minutes as we use condition to scan latency history inserted in the last 5 minutes,
USE distribution 
GO

DECLARE @subject SYSNAME
DECLARE @body VARCHAR(4000)
DECLARE @SubscriberTime VARCHAR(20)
DECLARE @PublisherTime VARCHAR(20)
DECLARE @TotalTime VARCHAR(20)
DECLARE @PublisherDB VARCHAR(20)
DECLARE @Publication VARCHAR(20)
DECLARE @Subscriber VARCHAR(20)
DECLARE @SubscriberDB VARCHAR(20)

SELECT @PublisherDB = publisher_db,
@Publication = publication,
@Subscriber = name,
@SubscriberDB = subscriber_db,
@SubscriberTime = RIGHT('0' + Cast([timetosubscriber]/3600 AS VARCHAR(3))
, 2)
+ ':'
+ RIGHT('0' + Cast(([timetosubscriber] % 3600) / 60 AS
VARCHAR
(2)), 2)
+ ':'
+ RIGHT('0' + Cast(([timetosubscriber] % 60) AS VARCHAR
(2)), 2
),
@PublisherTime = RIGHT('0' + Cast([timetopublisher]/3600 AS VARCHAR(3)),
2)
+ ':'
+ RIGHT('0' + Cast(([timetopublisher] % 3600) / 60 AS
VARCHAR(2
)), 2)
+ ':'
+ RIGHT('0' + Cast(([timetopublisher] % 60) AS VARCHAR(2
)), 2),
@TotalTime = RIGHT('0' + Cast([totaltime]/3600 AS VARCHAR(3)), 2)
+ ':'
+ RIGHT('0' + Cast(([totaltime] % 3600) / 60 AS VARCHAR(2)),
2)
+ ':'
+ RIGHT('0' + Cast(([totaltime] % 60) AS VARCHAR(2)), 2)
FROM (SELECT DISTINCT msda.publisher_db,
syss.name,
msda.subscriber_db,
msda.publication,
publisher_commit,
distributor_commit,
Datediff(ss, publisher_commit, distributor_commit) AS
[TimeToPublisher],
subscriber_commit,
Datediff(ss, distributor_commit, subscriber_commit) AS
[TimeToSubscriber],
Datediff(ss, publisher_commit, distributor_commit)
+ Datediff(ss, distributor_commit, subscriber_commit) AS
[TotalTime]
FROM mstracer_history msth
INNER JOIN msdistribution_agents msda
ON msth.agent_id = msda.id
INNER JOIN sys.servers syss
ON msda.subscriber_id = syss.server_id
INNER JOIN mstracer_tokens
ON msth.parent_tracer_id = mstracer_tokens.tracer_id
WHERE subscriber_commit > Dateadd(mi, -5, Getdate())) res
WHERE ( [timetopublisher] > 60
OR [timetosubscriber] > 60 )
-- Fetch if publisher to distributor or distributor to subscriber latency greater than 60 seconds
ORDER BY [totaltime] DESC

SET @subject='Replication Latency Alert'
SET @body=
'Replication latency exceeded the highest acceptable replication delay'
SET @body=@body
+ 'Publisher to Distributor: ' + @PublisherTime
+ 'Distributor to Subscriber: '+ @SubscriberTime
+ 'Total Delay: '+ @TotalTime
+ 'Publication: '+ @Publication
+ 'Subscriber: ' + @Subscriber

IF ( @body IS NOT NULL )
BEGIN
EXEC msdb.dbo.Sp_send_dbmail
@recipients = 'prajapatipareshm@gmail.com',
@subject = @subject,
@body = @body,
@profile_name = '<Profile name>',
@body_format = 'HTML';
END
This is the details I wanted to present here to catch up replication latency and hope you may like it.

The row was not found at the Subscriber when applying the replicated command - Alternate workaround - SQL Server Replication by serverku

Before a week ago, I shared one post related to this title. Please read first workaround for same. I hope you liked it. Here I would like to share another way which may drive towards an alternative solution to get it resolved.

Alternate workaround :  tablediff utility
In first workaround in the last post, we used some script to get missing rows or the rows where we had an issue and applied at subscriber to complete it. But here we have another method to get missing rows and can apply at the destination. Before moving this method, I would like to read the following post related to same.
  1. The row was not found at the Subscriber when applying the replicated command-Replication error in SQL Server
  2. SQL Server tablediff Utility – Introduction
  3. SQL Server tablediff utility for multiple tables using SSIS
  4. Apply discrepancies at destination using SSIS - tablediff Utility in SQL Server
Did you read all posts? Ok, now we can go ahead. Actually, you know the workaround after reading above posts, Even let me share too. Yes, we can do it with tablediff utility. With following above links below is the script in context to the same server and following databases\tables again with transactional replication,
  • Primary database : Test
  • Secondary database : Test1
  • Replicated table : dbo.sample1
"C:\Program Files\Microsoft SQL Server\90\COM\tablediff.exe" 
-sourceserver [DemoServer]
-sourcedatabase [test]
-sourceschema [dbo]
-sourcetable [sample1]
-sourceuser [sa]
-sourcepassword [test@1234]
-destinationserver [DemoServer]
-destinationdatabase [test1]
-destinationschema [dbo]
-destinationtable [sample1]
-destinationuser [sa]
-destinationpassword [test@1234]
-et Difference
-f C:\DiffOutput
Make sure above statement must be in single line statement.

After running above script which will compare two tables data which have an issue (we have already script to know tables having an issue from first workaround) from source database\table and destination\table and we have generated missing rows script SQL file at C:\DiffOutput and file content as follows,
-- Host: [DemoServer]
-- Database: [test1]
-- Table: [dbo].[sample1]
INSERT INTO [test1].[dbo].[sample1] ([id],[name]) VALUES (2,'test2')
This will also generate delete script for the rows which exists at the destination but does not exist at source, insert script for missing rows from source to destination and update script if whole rows are different if it have, but in our case we have only insert script. Please take a note this is another alternate solution and tablediff utility may degrade performance for large tables or tables having so many numbers of rows. But this may help you to achieve your happy solution if you do not aware first workaround.

Delete database backup history in SQL Server by serverku

As I have written the article to clean up the old database backup for the maintenance activities. The same thing i am doing here as a maintenance activity, but not for the clean up of database backups, It is for database backups history cleanup from MSDB database. Please read my earlier posts related database backup, you may like them.
  1. Database Backup Statistics and History
  2. Archive old database backup files using forfiles.exe and FOR /F
  3. Archive old database backup files using TSQL Script
It is required to clean up the database backup history periodically if no longer needed. Because if the msdb database has more history then it will take the time to load it or sometime it will fail to load because of time out. The script to clean up the database backups, history and a demo are as follows, First we will look for the history of all the database backups done by this SQL instance.
USE msdb 
GO

SELECT bs.database_name,
bs.backup_start_date,
CASE bs.type
WHEN 'D' THEN 'Full Backup'
WHEN 'I' THEN 'Diff Backup'
WHEN 'L' THEN 'Log Backup'
END AS BackupType,
bmf.physical_device_name
FROM msdb..backupset bs
INNER JOIN msdb..backupmediafamily bmf
ON ( bs.media_set_id = bmf.media_set_id )
ORDER BY bs.backup_start_date DESC

We have two methods to delete the database backup history.

#1. Based on DateTime By passing the date in stored procedure , SP will delete all the database history older then specified date time. Let us run below query and get the output.
DECLARE @BackupOlderdate DATETIME
SET @BackupOlderdate = '2011-05-17 14:22:13.000'
EXEC sp_delete_backuphistory @BackupOlderdate
GO

#2. Based on Database
By passing the Database name in stored procedure, SP will delete all the database history for specified database only. Let us run below query and get the output.
DECLARE @DBname sysname
SET @DBname = 'trialmaster'
EXEC sp_delete_database_backuphistory @DBname
GO

Please comment here if you know any other methods to delete it.

Sunday, 3 May 2015

Find running scheduled jobs in SQL Server - Alternate way by serverku

A few days before, I just posted one article to check running scheduled jobs and I used master. dbo. xp_sqlagent_enum_jobs system objects and joined with dbo.sysjobs object from the msdb database for the same. Please read that post before moving down. This was one way to get the list of running jobs and now here I am sharing another alternate way to find same details. For this I am using dbo. sp_help_job objects from msdb database and @execution_status parameter to get the details. Let me share a script here,
USE msdb
GO

–- 1- Executing
EXEC dbo.sp_help_job @execution_status = 1;
And the result looks,


@execution_status parameter status values are following for which you list out the jobs with that passed status,

0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.

You may be using this script to get job status. Please put your comments if any other alternate way you have other than these.

Saturday, 2 May 2015

Script to get running schedule jobs - SQL Server by serverku

A few days back, while I was working with Alerts for failed scheduled jobs and missing scheduled jobs, I was needed to exclude running jobs. So we can exactly know which jobs are actually failed excluding running jobs and sane case for missing jobs. I applied some additional in the existing script to fetch the records of failed scheduled jobs or missing jobs. Let me share a script here to get all running scheduled jobs,
USE msdb
GO

CREATE TABLE #RunningJobs
(
job_id UNIQUEIDENTIFIER NOT NULL,
last_run_date INT NOT NULL,
last_run_time INT NOT NULL,
next_run_date INT NOT NULL,
next_run_time INT NOT NULL,
next_run_schedule_id INT NOT NULL,
requested_to_run INT NOT NULL,
request_source INT NOT NULL,
request_source_id sysname COLLATE database_default NULL,
running INT NOT NULL,
current_step INT NOT NULL,
current_retry_attempt INT NOT NULL,
job_state INT NOT NULL
)

INSERT INTO #RunningJobs
EXECUTE master.dbo.xp_sqlagent_enum_jobs 1,'sa'

SELECT sj.name,
rj.*
FROM #runningjobs rj
INNER JOIN dbo.sysjobs sj
ON ( sj.job_id = rj.job_id )
WHERE rj.running = 1

DROP TABLE #RunningJobs
Above script use dbo.xp_sqlagent_enum_jobs undocumented object from the master database. It is also useful to get all other state values of jobs like following which received from forums,
0 = Not idle or suspended,
1 = Executing,
2 = Waiting For Thread,
3 = Between Retries,
4 = Idle,
5 = Suspended,
6 = WaitingForStepToFinish,
7 = PerformingCompletionActions
I am using this script in failed jobs and missing jobs list. You might be using it somewhere, Please share your comments. I will publish further posts to get failed jobs and missing jobs list.

Moving table or indexes on another filegroup - SQL Server by serverku

Because of data growth and performance issue we need to move tables or indexes to other file groups. The purpose of moving tables or indexes to improve the database performance as it reduces I/O from single drive or single filegroup. We can create another filegroup and move the tables and indexes to new created filegroups, then it will spit the I/O to two different filegroups. This way it will improve performance.

When we need to move the tables or indexes to another filegroup? We should move those table needs to move which are having more rows or heavily in size, Also need to move if those table's data are frequently updated. Here I would like to show the demo for the same. Let us see how can we move tables/indexes to another filegroup.
-- First we are creating database  
-- Main primary file on Primary filegroup
-- Secondary files on secondary filegroup.
-- Log files on different file group.
CREATE DATABASE filegroupdb
ON PRIMARY
( name = filegroupdb_data,
filename = 'C:\FileGroupDB_Data.mdf',
size = 4 mb,
maxsize = 5 mb,
filegrowth = 1 mb ),
filegroup secfilegroup
( name = filegroupdb_data_1,
filename = 'C:\FileGroupDB_Data_1.ndf',
size = 2 mb,
maxsize = 5 mb,
filegrowth = 1 mb )
log ON
( name = filegroupdb_log,
filename = 'C:\FileGroupDB_Log.ldf',
size = 2 mb,
maxsize = 5 mb,
filegrowth = 1 mb )

GO
After creating database we will create a new table on Primary filegroup. If you not mentioned filegroup name, then it will be created on default filegroup. Let us create it.
USE filegroupdb 
GO

-- Creating table on Primary filegroup
IF( Object_id('tblFileGroup', 'u') > 0 )
DROP TABLE tblfilegroup
GO

CREATE TABLE tblfilegroup
(
objectid INT NOT NULL PRIMARY KEY,
objectname VARCHAR(100),
createdate DATETIME
)
ON [PRIMARY]

GO
The table is created and now we look the property of the table where it is created,

SP_HELP tblFileGroup

Now we are coming to the point which is tables/indexes actually will be moved. There are two ways through we can move the tables and indexes.

#1. By moving clustered index
Using this way we just need to move clustered index and tables and all indexes will be moved to different filegroup.

How can with #1 way?
-- Defining dropping constraint with move
ALTER TABLE tblFileGroup
DROP CONSTRAINT PK__tblFileG__9A619291029E5EB6 WITH (MOVE TO SecFileGroup)
GO

-- Adding constraint
ALTER TABLE tblFileGroup
ADD CONSTRAINT PK__tblFileG__9A619291029E5EB6 PRIMARY KEY(ObjectId)
GO
Let us check again the properties of tables as successfully moved or not.

SP_HELP tblFileGroup

#2. Recreate a clustered index with drop existing
We just need to recreate a table's clustered index with drop existing clustered index on that.

How can with #2 way?
CREATE UNIQUE CLUSTERED INDEX PK__tblFileG__9A619291029E5EB6
ON tblFileGroup(ObjectId)
WITH DROP_EXISTING
ON SecFileGroup

GO
You also worked with moving tables/indexes to another location, Share your ideas here!