Solved

T-SQL for SQL Server 2008 to detemine who is Principal and who is Mirror

Posted on 2012-12-30
15
1,055 Views
Last Modified: 2012-12-31
I have setup mirroring for a database using SQL Server 2008 SP2.

When I look in the SQL Mgmt Studio my SQL1 server shows as (Principal, Synchronized) and my SQL2 server shows as (Mirror, Synchronized/Restoring...).

When I issue the follow T-SQL:

USE [Master]
GO
ALTER DATABASE [$(varDB)] SET PARTNER FAILOVER
GO

The GUI shows the reverse.  i.e SQL2 is now Principal and SQL1 is now Mirror.

Is there some T-SQL code I can use to show the Principal and Mirror status for the database?
0
Comment
Question by:Carl Webster
  • 8
  • 4
  • 3
15 Comments
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 38732390
from the docs: http://msdn.microsoft.com/en-us/library/bb522476.aspx
To learn the role and state of the database mirroring endpoint of a server instance, on that instance, use the following Transact-SQL statement:
SELECT role_desc, state_desc FROM sys.database_mirroring_endpoints

Open in new window

0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732447
For both servers that shows, PARTNER, STARTED.  It doesn't tell me who is currently the Principal or Mirror.

I found this:

select mirroring_state_desc,mirroring_role_desc from sys.database_mirroring where database_id =(select database_id from sys.databases where name='DBName')

That tells me who is Principal and who is Mirror but, since I can barely spell SQL, I can't figure out how to run this from one SQL 2008 SP2 server and get the info from both SQL servers.

In my case, I have two SQL servers: SQL1 and SQL2 and the database name is Data_Store.

How can I run the code from SQL1 and get the info for SQL2?
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 38732585
if the 2 servers have a linked server setup to point to the other, yes, you should be able to run this via linked server on the "other" server.
0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732593
May I ask you how to setup the linked server?  Do you need to know anything besides the 2 server names and the database name?
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 38732601
it's quite easy from the GUI:
http://msdn.microsoft.com/en-us/library/ff772782.aspx
you specify the linked server's name, and eventually specify the security tab's settings if the login name/passwords are not the same...
that's it
0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732718
I need to have a script I can use, so using the T-SQL examples from your link I came up with:

USE [master]
GO
EXEC master.dbo.sp_addlinkedserver @server = N'SQL2', @srvproduct=N'SQL Server' ;
GO
USE [master]
GO
EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname = N'SQL2', @locallogin = NULL, @useself = N'True' ;
GO

SELECT name FROM [SQL2].master.sys.sysdatabases ;
GO

But what I get are the databases on SQL1.

name                                                                                                                            
----------------------
master                                                                                                                          
tempdb                                                                                                                          
model                                                                                                                          
msdb                                                                                                                            
Data_Store            
Config_Log

The Config_Log database does not exist on SQL2.
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 38732754
not sure about why that happens.
I don't have sql servers available during my "off time" to play with this... :(
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 51

Accepted Solution

by:
Mark Wills earned 500 total points
ID: 38732813
You shouldnt have to worry (about query on the other server) - in a mirror, they must be one or the other of Principal or Mirror.

So if SQL1 is Principal then SQL2 must be Mirror. You might want to check to see that they are fully synchronised...

The "normal" query to check is :

SELECT db.name, m.mirroring_role_desc, m.mirroring_state_desc, m.mirroring_role_sequence 
FROM sys.database_mirroring m 
JOIN sys.databases db
ON db.database_id = m.database_id
WHERE db.name = N'whatever_my_dbname_is'; 
GO

Open in new window


That should return Principal or Mirror, and the other column of interest is that state description.

When you issue the SET PARTNER FAILOVER you are effectively performing a manual failover and so the roles are indeed reversed.

You can see how many times the roles have swapped with m.mirroring_role_sequence

There really shouldnt be any need to query the other database, it simply cannot have two principals (or it is broken and the other server is not available or not fully synch'd so no failover is possible)

Worthwhile checking out those system mirror views : http://msdn.microsoft.com/en-us/library/ms178655(v=sql.100).aspx

If you have by chance set up a witness then there is good summary information in sys.database_mirroring_witnesses  also note the other links to these other views down the bottom of the link above.
0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732877
Yes this is setup with a Witness server.

This is what I came up with using your sample code:

set nocount on;
go
SELECT 'Database Name' = Left(db.name,25), 'Mirror Role' = Left(m.mirroring_role_desc,15), 'Mirror State' = Left(m.mirroring_state_desc,15), '# Times Failed Over' = left(m.mirroring_role_sequence,15)
FROM sys.database_mirroring m
JOIN sys.databases db
ON db.database_id = m.database_id
WHERE db.name = N'Data_Store';
GO

Output is:

Database Name     Mirror Role     Mirror State    # Times Failed Over
------------------------- --------------- --------------- -------------------
DATA_STORE         PRINCIPAL       SYNCHRONIZED    3            

hmmm, just a sec.  Let me try just one more thing.
0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732894
OK, got what I need now.

I created a batch file to gather parameters and then passed it to sqlcmd.

REM %1 is the principal sql server
REM %2 is the mirror sql server
REM %3 is the database name

echo Results for SQL Server: %1 >  c:\install\xenapp\logs\VerifyPrincipalMirrorLog1.txt
sqlcmd -S %1 -V 25 -v varDB=%3 -i c:\install\xenapp\VerifyPrincipalMirror.sql >> c:\install\xenapp\logs\VerifyPrincipalMirrorLog1.txt
if errorlevel 1 goto Error1

echo Results for SQL Server: %2 >  c:\install\xenapp\logs\VerifyPrincipalMirrorLog2.txt
sqlcmd -S %2 -V 25 -v varDB=%3 -i c:\install\xenapp\VerifyPrincipalMirror.sql >> c:\install\xenapp\logs\VerifyPrincipalMirrorLog2.txt
if errorlevel 1 goto Error2

Log1 is:

Results for SQL Server: SQL1
Database Name             Mirror Role     Mirror State    # Times Failed Over
------------------------- --------------- --------------- -------------------
DATA_STORE                PRINCIPAL       SYNCHRONIZED    3                  

Log2 is:

Results for SQL Server: SQL2
Database Name             Mirror Role     Mirror State    # Times Failed Over
------------------------- --------------- --------------- -------------------
DATA_STORE                MIRROR          SYNCHRONIZED    3                  

That will satisfy the QA people who want to see both servers.

Thanks for all the help.
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 38732895
OK, then there is also the mirror_server_name and principal_server_name in sys.database_mirroring_witnesses that you can check...
0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732906
Oh, sorry, here is my .sql file:

set nocount on;
go
SELECT 'Database Name' = Left(db.name,25), 'Mirror Role' = Left(m.mirroring_role_desc,15), 'Mirror State' = Left(m.mirroring_state_desc,15), '# Times Failed Over' = left(m.mirroring_role_sequence,15)
FROM sys.database_mirroring m
JOIN sys.databases db
ON db.database_id = m.database_id
WHERE db.name = N'$(varDB)';
GO

EE and MSDN are good resources for learning some basic SQL and T-SQL stuff. :)
0
 
LVL 36

Author Comment

by:Carl Webster
ID: 38732910
On SQL1 (what I call my principal SQL server in my little lab setup),

select * FROM sys.database_mirroring_witnesses

returns 0 rows

Or should that be run on the Witness server (SQLWitness in my lab)?
0
 
LVL 51

Expert Comment

by:Mark Wills
ID: 38732924
Yep, on SQLWitness...

But it looks like you have a good working solution with your batch job - also provides "security" for your QA people being run from a process (ie sqlcmd) external to the SQL servers in being the same query but applied specifically to your individual servers.

You could add into your select statement an additional column : @@servername as Server

That way the logs will be self documenting (and maybe throw in a getdate() so you gain visibility on period).
0
 
LVL 36

Author Closing Comment

by:Carl Webster
ID: 38732934
Thanks for the help.  You gave me the "bone" I needed to go dig a little further and come up with something that works for my specific situation.

I hope the info I left on how I took your code and made it fit what I needed may help someone else in the future.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Hi all, It is important and often overlooked to understand “Database properties”. Often we see questions about "log files" or "where is the database" and one of the easiest ways to get general information about your database is to use “Database p…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now