SQL Server security best practice

Security! This is the word comes in mind of every concerned person when it come...

Change the Collation Settings in MS SQL Server

This post will show you how to change the collation settings in MS SQL Server for specific database...

Resolve collation conflict

In this post I will show you how you can resolve collation conflict error...

Book: SQL Server 2008 High Availability

In this book I have tried to cover every single piece of information that might requires for installing and configuring SQL Server HA option like Clustering, Replication, Log Shipping and Database Mirroring...

Why to recompile Stored Procedure

Generally, we create views and stored procedures (proc here after) ...

12/25/2012

SQL Server # Moving MASTER database in cluster environment

Few months back I have wrote post about moving MASTER and MSDB database to new location in stand alone machine.

In recent past we had a situation where customer asked us to move MASTER database to new location, below are the steps I have taken:

  1.     Connect to the Server
  2.     Open Configuration Manager -> SQL Server Service
  3.     Right Click and say Properties
  4.     Click on the Start-up Parameter
  5.     Remove start-up parameter (the highlighted one)
	 -dOLDLocation\master.mdf
-eOLDLocation\ErrorLog
-lOLDLocation\mastlog.ldf



 



      6.     Add new start-up parameters with new values (per your configuration)

   




	 -dNewLocation\master.mdf
-eNewLocation\ErrorLog
-lNewLocation\mastlog.ldf



      7.    Check and confirm which node is active

      8.    PAUSE current PASSIVE Node  to avoid fail-over


      9.    Take SQL Server resources offline, i.e. SQL Server, SQL Agent, MSDTC, SQLCLUSTER Name (do not take SQL Cluster IP Offline)


    10.    Copy MASTER.MDF and MASTLOG.LDF to NEW Location ( S:\SQLDATA, yours could be different)


    11.    Log into Cluster Administrator and bring SQL Server Resources online


    12.    Resume current PASSIVE Node



 



That's all, you should be able to see your master database on new location now!!!



 



-- Regards,



Hemantgiri S. Goswami (http://www.sql-server-citation.com )



Cross posting: http://www.pythian.com/news/35829/moving-master-database-to-new-location-in-sql-cluster/

10/18/2012

SQL Server Database Backup Report using T-SQL

Today, I am going to share few very useful scripts which will report us on Database Backup from different view points. To get the List/History/Log of all the Successful Backups
SELECT 

  b.machine_name,

  b.server_name,

  b.database_name as DBName,

  b.backup_start_date,

  b.backup_finish_date,

  CASE 

    WHEN b.[type] = 'D' THEN 'Database'

    WHEN b.[type] = 'I' THEN 'Differential database'

    WHEN b.[type] = 'L' THEN 'Log'

    WHEN b.[type] = 'F' THEN 'File or filegroup'

    WHEN b.[type] = 'G' THEN 'Differential file'

    WHEN b.[type] = 'P' THEN 'Partial'

    WHEN b.[type] = 'Q' THEN 'Differential partial'

    ELSE b.[type]

  END Backup_Type,    

  b.expiration_date,

  b.[user_name],

  DATEDIFF(MINUTE,b.backup_start_date ,b.backup_finish_date) as Total_Time_in_Minute,

  b.recovery_model,

  b.backup_size/(1024 * 1024 * 1024) as Total_Size_GB,

  bf.physical_device_name as Location

FROM 

  msdb.dbo.backupset AS b

INNER JOIN msdb.dbo.backupmediafamily AS bf

  ON b.media_set_id=bf.media_set_id

ORDER BY 

  b.backup_start_date DESC

GO
To get a list of all successful Backups taken till date for a particular Database
DECLARE @DBName AS VARCHAR(100) = 'Your Database Name'
SELECT 

  b.machine_name,

  b.server_name,

  b.database_name as DBName,

  b.backup_start_date,

  b.backup_finish_date,

  CASE 

    WHEN b.[type] = 'D' THEN 'Database'

    WHEN b.[type] = 'I' THEN 'Differential database'

    WHEN b.[type] = 'L' THEN 'Log'

    WHEN b.[type] = 'F' THEN 'File or filegroup'

    WHEN b.[type] = 'G' THEN 'Differential file'

    WHEN b.[type] = 'P' THEN 'Partial'

    WHEN b.[type] = 'Q' THEN 'Differential partial'

    ELSE b.[type]

  END Backup_Type,

  b.expiration_date,

  b.[user_name],

  DATEDIFF(MINUTE,b.backup_start_date ,b.backup_finish_date) as Total_Time_in_Minute,

  b.recovery_model,

  b.backup_size/(1024 * 1024 * 1024) as Total_Size_GB,

  bf.physical_device_name as Location

FROM 

  msdb.dbo.backupset AS b

INNER JOIN msdb.dbo.backupmediafamily AS bf

  ON b.media_set_id=bf.media_set_id

WHERE

  b.database_name = @DBName  

ORDER BY 

  b.backup_start_date DESC

GO
To get the List of all Databases which are not backed up till date
SELECT

  d.name [DB_Name]

FROM

  master.sys.databases d

LEFT JOIN msdb.dbo.backupset b

  ON b.database_name = d.name

WHERE

  d.database_id IS NULL
To get the List of all Databases which are not backed up since last X days
DECLARE @LastXDays AS INT = 1

;WITH LatestBackupSet AS (

SELECT 

  b.database_name as DBName,

  b.backup_start_date LastBackedUpOn,

  b.[user_name],

  ROW_NUMBER() OVER(PARTITION BY b.database_name ORDER BY b.backup_start_date DESC) Rnk

FROM 

  msdb.dbo.backupset AS b

)

SELECT 

  lbs.DBName,

  lbs.LastBackedUpOn,

  lbs.[user_name]

FROM 

  LatestBackupSet AS lbs

WHERE

  DATEDIFF(DAY,lbs.LastBackedUpOn ,CURRENT_TIMESTAMP) = @LastXDays  

  AND lbs.Rnk = 1

ORDER BY 

  lbs.DBName DESC

GO
To get a list of the Latest successful backups of all Databases
;WITH LatestBackupSet AS (

SELECT 

  b.machine_name,

  b.server_name,

  b.database_name as DBName,

  b.backup_start_date,

  b.backup_finish_date,

  CASE 

    WHEN b.[type] = 'D' THEN 'Database'

    WHEN b.[type] = 'I' THEN 'Differential database'

    WHEN b.[type] = 'L' THEN 'Log'

    WHEN b.[type] = 'F' THEN 'File or filegroup'

    WHEN b.[type] = 'G' THEN 'Differential file'

    WHEN b.[type] = 'P' THEN 'Partial'

    WHEN b.[type] = 'Q' THEN 'Differential partial'

    ELSE b.[type]

  END Backup_Type,

  b.expiration_date,

  b.[user_name],

  DATEDIFF(MINUTE,b.backup_start_date ,b.backup_finish_date) as Total_Time_in_Minute,

  b.recovery_model,

  b.backup_size/(1024 * 1024 * 1024) as Total_Size_GB,

  bf.physical_device_name as Location,

  ROW_NUMBER() OVER(PARTITION BY b.database_name ORDER BY b.backup_start_date DESC) Rnk

FROM 

  msdb.dbo.backupset AS b

INNER JOIN msdb.dbo.backupmediafamily AS bf

  ON b.media_set_id=bf.media_set_id

)

SELECT 

  machine_name,

  server_name,

  DBName,

  backup_start_date,

  backup_finish_date,

  Backup_Type,

  expiration_date,

  [user_name],

  Total_Time_in_Minute,

  recovery_model,

  Total_Size_GB,

  Location

FROM 

  LatestBackupSet AS lbs

WHERE

  lbs.Rnk = 1

ORDER BY 

  lbs.DBName DESC

GO
To get the Latest successful backup of a particular Database
DECLARE @DBName AS VARCHAR(100) = 'Your Database Name'

 

;WITH LatestBackupSet AS (

SELECT 

  b.machine_name,

  b.server_name,

  b.database_name as DBName,

  b.backup_start_date,

  b.backup_finish_date,

  CASE 

    WHEN b.[type] = 'D' THEN 'Database'

    WHEN b.[type] = 'I' THEN 'Differential database'

    WHEN b.[type] = 'L' THEN 'Log'

    WHEN b.[type] = 'F' THEN 'File or filegroup'

    WHEN b.[type] = 'G' THEN 'Differential file'

    WHEN b.[type] = 'P' THEN 'Partial'

    WHEN b.[type] = 'Q' THEN 'Differential partial'

    ELSE b.[type]

  END Backup_Type,

  b.expiration_date,

  b.[user_name],

  DATEDIFF(MINUTE,b.backup_start_date ,b.backup_finish_date) as Total_Time_in_Minute,

  b.recovery_model,

  b.backup_size/(1024 * 1024 * 1024) as Total_Size_GB,

  bf.physical_device_name as Location,

  ROW_NUMBER() OVER(PARTITION BY b.database_name ORDER BY b.backup_start_date DESC) Rnk

FROM 

  msdb.dbo.backupset AS b

INNER JOIN msdb.dbo.backupmediafamily AS bf

  ON b.media_set_id=bf.media_set_id

WHERE

  b.database_name = @DBName  

)

SELECT 

  machine_name,

  server_name,

  DBName,

  backup_start_date,

  backup_finish_date,

  Backup_Type,

  expiration_date,

  [user_name],

  Total_Time_in_Minute,

  recovery_model,

  Total_Size_GB,

  Location

FROM 

  LatestBackupSet AS lbs

WHERE

  lbs.Rnk = 1

ORDER BY 

  lbs.DBName DESC

GO
To get a list of Databases that were backed-up and do not currently exist
SELECT

  DISTINCT b.database_name

FROM

  msdb.dbo.backupset b

WHERE

  DB_ID(b.database_name) IS NULL
Hope, the above given script will be of help to you. Also, I would like to request you to please add any relevant script which you feel would be useful as a comment.

10/15/2012

SQL Server # TSQL to Convert STRING in PROPER format

Problem Statement

SQL Server has got in-built functions to convert the given string into LOWER() or UPPER() format but it does not provides any direct way to convert it to PROPER format. A string/text is said to be in a PROPER format if all the words in that string/text starts with a CAPITAL letter.

E.g. If a string is - “Hello, how are you?”,

String in Lower format = “hello, how are you?”

String in Upper format = “HELLO, HOW ARE YOU?”

and String in Proper format = “Hello, How Are You?”

 

Implementation

Ideally, SQL Server is not the right place to implement this kind of logic, as string operations are costlier in SQL from performance perspective. it should be either implemented in the Front-End language or the Reporting Tool as this more related to the formatting. However, if this is to be implemented in SQL, the more preferred way is to use SQL-CLR function. It does not mean that we can not achieve this with T-SQL.

Today, I will share a simple T-SQL function, which could be used to convert any given string in PROPER format. Below is the script -

CREATE FUNCTION [dbo].[PROPER]



(



  @StrToConvertToProper AS VARCHAR(MAX)



) 



RETURNS VARCHAR(MAX) 



AS



BEGIN



  --Trim the Text



  SET @StrToConvertToProper = LTRIM(RTRIM(@StrToConvertToProper))



 



  --Find the No. of Words in the Text



  DECLARE @WordCount AS INT



  SET @WordCount = LEN(@StrToConvertToProper) - LEN(REPLACE(@StrToConvertToProper,' ','')) + 1



 



  --Variable to track the space position



  DECLARE @LastSpacePosition AS INT = 0



 



  --Loop through all the words



  WHILE(@WordCount > 0)



    BEGIN



      --Set the Space Position



      SET @LastSpacePosition = CHARINDEX(' ',@StrToConvertToProper,@LastSpacePosition + 1)



      



      --Replace the Character



      SET @StrToConvertToProper = STUFF(@StrToConvertToProper,



                                        @LastSpacePosition + 1,



                                        1,



                                        UPPER(SUBSTRING(@StrToConvertToProper, @LastSpacePosition + 1, 1)))



      --Decrement the Loop counter                                      



      SET @WordCount = @WordCount - 1



    END



    



  RETURN @StrToConvertToProper



END  




When the above script is used as –





SELECT dbo.PROPER('hello, how are you?')






we get the following result - Hello, How Are You?



Conclusion



The given script could be used to convert any string in PROPER format using T-SQL. However, I would personally prefer converting the string at the Front-End or in the Reporting tool to display the string in this format.

9/02/2012

Troubleshooting Oracle Link Server - Part2


It's my bad that I did not made a post since long lately. I would not make an excuse like I was busy, rather, I would say I am little lazy DBA, but I now onward I will try to post blog more frequently.

Well, if you remember, earlier I have posted some tips about troubleshooting Link Server issue for Oracle, today I will be posting one more tip to the list aka extending Troubleshooting Oracle Link Server. 

Few weeks back one of the developer reached out to me needing an assistance with Oracle Link Server. The issue with him was, whenever he execute T-SQL against Oracle Link Server, SQL Server was throwing an error at him which reads like OLE DB provider "OraOLEDB.Oracle" for linked server "XXXXXX" returned message "Cannot start more transactions on this session." I'd connected to the server using SSMS and have checked permissions, Link Server and Provider configuration - nothing was changed. Then what could have cause this error? well, I will need to RDP to the box then to find an answer.     

But before that, as usual, upon questionnaire session, I came to know that developers doesn't have direct access to box and they all were using Citrix to connect to the SQL Server box hence they would not have any idea on what's going on with the physical box. As a DBA I had a privileges to RDP to the development box (obviously ), as soon as I logged in I'd notice that the box is running out of space. The drive which was running out of space was hosting:
  • User Profiles
  • TempDB
  • & UserDB which they were using for ETL purpose for Oracle
And, as expected, once I'd reclaim some space everything was back to normal. 

Regards
Hemantgiri S. Goswami (http://www.sql-server-citation.com )

3/28/2012

SQL Server # Storing Hierarchical Data – Parent Child n’th level # TSQL

Introduction

Today, I would like to explain one way in which we can store the HIERARCHICAL data in SQL tables. A general table structure which people come up to store this kind of data is -

1

Where, EmployeeID id the UniqueID alloted to every new employee record inserted into the table and ManagerID is the EmployeeID of the immediate manager of the employee. Keeping in mind that Manager is also an employee.

Problem Statement

This table structure very well serves the purpose as long as we have 1-Level hierarchy. However, if the hierarchy is of n'th level, the SELECT statement to fetch the records becomes more complex with this kind of table structure. Suppose, we want to fetch the complete TREE of a particular employee, i.e. list of all the employees who are directly or indirectly managed by a particular employee. How to do it……..?

Thanks to CTE’s for making the life a bit easier – as using them in a recursive manner, we can get the work done. Please follow this msdn link to see an implementation using recursive CTE.

Suggested Table Structure

2

Here, I have just included a new column [PATH]. It is of VARCHAR(MAX) type. I have taken it as VARCHAR(MAX) just to make sure the field is long enough to store the complete path. But one can assign appropriate size as per their system’s requirement.

The basic idea of the [path] column is to store the complete hierarchical path of any employee separated by a delimiter as under -

3

Calculating the new path is very simple. It’s just, {New Path} = {Parent Path} + {Self ID} + {Delimiter}

Now, suppose if I want to fetch all the employees who are directly or indirectly working under EmployeeID = 2, I can use the below tsql -

;WITH CTE AS (
SELECT 1 EmployeeID,NULL ManagerID, '\1\' [Path]
UNION ALL    
SELECT 2 EmployeeID,1 ManagerID, '\1\2\' [Path]
UNION ALL    
SELECT 3 EmployeeID,1 ManagerID, '\1\3\' [Path]
UNION ALL    
SELECT 4 EmployeeID,2 ManagerID, '\1\2\4\' [Path]
UNION ALL    
SELECT 5 EmployeeID,4 ManagerID, '\1\2\4\5\' [Path]
)
SELECT
  *
FROM
  CTE
WHERE
  [Path] LIKE '%\2\%'

We can use a simple logic to even find out the level of the Employee -


SELECT
  *,
  (LEN([Path]) - LEN(REPLACE([Path],'\',''))) - 2 [Level]
FROM
  CTE
WHERE
  [Path] LIKE '%\2\%'

4

2 is subtracted from the formula as the length of delimiter for Level-0 is 2.

Conclusion

Hope, this simple trick could save a lot of time for the ones who find themselves lost playing with the hierarchical data.

3/12/2012

Last Execution Date Time of a Stored Procedure

On many forums I have found a very basic yet important query - “How can I know when was my Stored Procedure last executed?” And today through this blog I will try to answer this question.
Actually speaking, without explicit logging or tracing, it is not possible to get this information for each and every Stored Procedure of our Database. However, we can get this detail along with many other relevant information for the stored procedure having it’s execution plan currently cached on the server by using - sys.dm_exec_procedure_stats It’s a system dynamic view that returns aggregate performance statistics for cached stored procedures.Please note that this view has been introduced from SQL Server 2008.
The important thing to note is that this view returns one row for each cached stored procedure plan, and the lifetime of the row is as long as the stored procedure remains cached. When a stored procedure is removed from the cache, the corresponding row is eliminated from this view.
So, let’s see a way, using which at least we can find out the some important facts for the cached stored procedures -
USE DBName
GO
SELECT 
 O.name,
 PS.last_execution_time
FROM 
 sys.dm_exec_procedure_stats PS 
INNER JOIN sys.objects O 
 ON O.[object_id] = PS.[object_id] 
GO
P.S. Please replace the DBName with the actual name of the Database.


The above script will return the name of all the cached stored procedure of the current database with their last execution time.


For more details on this dynamics view, please refer - sys.dm_exec_procedure_stats (Transact-SQL)

3/08/2012

Moving MASTER Database

In my previous post we see how to move MSDB database, today we will see how to move or relocate MASTER database. While moving MASTER database we’ll have to consider few other things like changing start-up parameter for SQL Server Service. I will also mention those stops here for better understanding. Let’s do it step-by-step.

Step 1: Query sys view and note down the existing location for MASTER database

USE MASTER 
GO 
SELECT 
NAME, 
PHYSICAL_NAME AS 'PhysicalFilePath', 
STATE_DESC AS 'DB Status' 
FROM SYS.MASTER_FILES 
WHERE NAME LIKE 'Mast%'

Screen001

Step 2: Run alter database command and change the location for database files

ALTER DATABASE MASTER 
MODIFY FILE 
( 
NAME = MASTER, 
FILENAME= 'C:\SQLDB\Demo\Master.mdf' 
) 
GO 
ALTER DATABASE MASTER 
MODIFY FILE 
( 
NAME = MastLog, 
FILENAME= 'C:\SQLDB\Demo\MastLog.mdf' 
) 
GO 

Screen002

Step 3: Stop SQL Server Service and move database files to new location

Step 4: Restart SQL Server Service, surprised ?

Screen003 

Step 5: This was expected, let’s see what errorlog has to say about this!

Screen004

Refer the highlighted section, SQL Server service could not find the files. This is because we have moved that files to new location.

Step 6: Okay, so let’s go and change the start-up parameter. We can do this using Configuration manager.

Step 7: Right click on SQL Server service –> Properties –> Start-up Parameter

Screen005

Step 8: Make correction in path for Master.mdf and Master.ldf

Step 9: Start SQL Server service, this time it will start.

You are done!!

Note: This is to be done when we have to do relocate databases to new drive, or file organization, or some error which force us to do this.

-- Hemantgiri S. Goswami

3/07/2012

Moving MSDB to new location

In recent past we have a situation where in we required to move MSDB, Model and Master databases to new location, the reason being faulty drive. While moving system databases to new location we need to be extra cautious. Let’s see the process step-by-step.
Step 1: Let’s query sys view and note down the location for database files

SELECT
NAME,
PHYSICAL_NAME AS 'PhysicalFilePath',
STATE_DESC AS 'DB Status'
FROM SYS.MASTER_FILES
Screen001
Step 2: Run alter database and specify new location for database
SELECT
ALTER DATABASE MSDB
MODIFY FILE
(
NAME = MSDBData,
FILENAME= 'C:\SQLDB\Demo\MSDBData.mdf'
)
GO
ALTER DATABASE MSDB
MODIFY FILE
(
NAME = MSDBLog,
FILENAME= 'C:\SQLDB\Demo\MSDBLog.ldf'
)
GO
Screen002
Step 3: Stop SQL Server service
Screen003
Step 4: Once SQL Server service is stopped move MSDB database to new location
Step 5: Now, start SQL Server service. This time it will use the new path that we have configured in Step 2.
Note: If you have enabled and configure Database Mail, please make sure it works after you moved MSDB to new location.

Tomorrow, I will post about how to relocate Master database.

-- Hemantgiri S. Goswami (http://www.sql-server-citation.com/)

3/06/2012

Register for SQL Server 2012 Virtual Launch

`As we all are aware SQL Server 2012 virtual launch is scheduled after 60 hours roughly. Earlier I have discussed what’s new in SQL Server 2012 setup, MS has released SQL Server 2012 training kit and made it available for us to download. In recent past, I have blogged about a free eBook for SQL Server 2012 written by Ross Mistry ( Blog | Twitter ) and Stacia Misner ( Blog | Twitter) .

You will see lots of new and insightful information on new and enhanced features introduced in SQL Server 2012, this includes:

  • AlwaysOn
  • Automating AlwaysOn management
  • New backup and restore capabilities
  • ColumnStore index
  • Semantic Search
  • User-defined server roles
  • Data quality service
  • StreamInsight for SQL Server 2012
  • Big data analytics and Hadoop
  • T-SQL Enhancements
  • SQL Server Data Tools (SSDT)
  • SQL Azure
    Sounds interesting ?
    Get yourself register for the event, you will find the agenda of the event here.

3/01/2012

Download free eBook for SQL Server 2012

Microsoft has released one more free eBook, this time it is on SQL Server 2012. However, this is the second draft of this book. SQL Server MVP Ross Mistry and Stacia Misner has covered Administration and BI part, there are 10 chapters in total divided in two part, they are:
0068.665156_excerpt2_3D19D01BPART I DATABASE ADMINISTRATION (by Ross Mistry)1. Denali Editions and Enhancements
2. High Availability and Disaster Recovery Enhancements
3. Scalability and Performance
4. Security Enhancements
5. Beyond Relational


PART II BUSINESS INTELLIGENCE DEVELOPMENT (by Stacia Misner)6. Integration Services
7. Data Quality Services
8. Master Data Services
9. Analysis Services and PowerPivot
10. Reporting Services


Want to read more and download an eBook for free ? Link –> Introducing Microsoft SQL Server 2012
For those who missed downloading eBook on SQL Server 2008, here is the link –> Introducing Microsoft SQL Server 2008 R2

Update : 2nd March 2012, Table of Content was wrong, thank you Stacia Misner (@staciamisner) .

-Hemantgiri S Goswami (http://www.sql-server-citation.com )

1/31/2012

When DBCC INPUTBUFFER disappoints

Today we have an alert from one of the client server about blocking, I have immediately start looking at it using below statement

 
SELECT * FROM 
MASTER..SYSPROCESSES
WHERE BLOCKED != 0 
Yes, I’ve found the culprit SPID that is occupying more resources, using DBCC INPUTBUFFER(SPID). so, instead of seeing what exactly this SPID is doing I have received SP_EXECUTESQL, surprised!!! No, it’s bound to happen when SPID is running dynamic TSQL (using SP_EXECUTESQL) and/or cursor. But, yes, at the same time I would like to know what it is running behind the scene. There are two options that came to my mind
  • Using Profiler
  • using function – ::fn_get_sql(@SQLHandle) 
I preferred to use 2nd option as this is one time effort (at least as of now), and, it would be very quick. So, here is what I have used
 

-- Variable that will store the SQLHandle
DECLARE @SQLHandle BINARY(20)

-- Variable that will pass on the culprit SPID
DECLARE @SPID INT

-- value for culprit SPID
SET @SPID = 52

-- this will give you the SQLHandle for the culprit SPID
SELECT @SQLHandle = SQL_HANDLE 
FROM MASTER..SYSPROCESSES 
WHERE SPID = @SPID  

-- this statement will give you the SQL Statement for culprit SPID
SELECT [TEXT] FROM ::FN_GET_SQL(@SQLHandle)
You must be thinking why I have used this function instead sys.dm_exec_sql_text? Any guess??
Yes, you are right, customer is still using SQL server 2000 {Winking smile}
BTW, if you happened to come across something relating but on SQL Server 2005 or SQL Server 2008 and greater I have a reference script for you

Erland Sommarskog, SQL Server MVP has written aba_lockinfo and a script a.k.a. Custom Blocker Report from Aaron_Bertrand.
 
--Hemantgiri S. Goswami (http://www.sql-server-citation.com )

1/30/2012

Rebuild System Databases

Yesterday night one of FB Friend have ping me, he has issue with his local SQL Server instance. Our conversation goes like:
FB Friend: Hi
I : Hi
FB Friend: I need your help
FB Friend : My SQL Server is not starting...
I : What is an error you are getting?
FB Friend : Just nothing
I : Ok, check the SQL Server Error Log and EventViewer
I : you can find errologs at C:\Program Files\Microsoft SQL Server\MSSQL11.DENALI\MSSQL\Log
I : open it with notepad ....
FB Friend: Ok
FB Friend: Cannot recover the master database. SQL Server is unable to run. Restore master from a full backup, repair it, or rebuild it. For more information about how to rebuild the master database, see SQL Server Books Online.
I : Wow, seems like your master database is corrupt, you will need to run repair or you may want to rebuild master database.
I : Is this a new installation ?
FB Friend : Yes, this is new installation, and, I don't want to re-run the installation again, what is my option ?
I : you will need to rebuild master or restore it
FB Friend: How do I do it?
I: Here are your steps

Rebuild Master:

Step 1: Insert your setup media CD or folder where you have dumped SQL Server Installation
Step 2: Open command prompt
Step 3: Go to location (wherever you have setup, Step 1)
Step 4: setup /ACTION=REBUILDDATABASE /QUIET /INSTANCENAME=MSSQLServer /SQLSYSADMINACCOUNTS=MyAdmin /SAPWD=somePwd

Step 5: this will pop up new command window and then disappears

Step 6: you will have to refer logs so as to see whether it was successful completed or exit with error

This is it, you system database has been rebuild successfully!!
Restoring Master Database - An alternative method:
Step 1: Take backup of master database, in your case, I assume, you already have your master database backed up.

Step 2: Stop SQL Server Services * you will need Administrator permission for this operation

Step 3: Start SQL Server using -C and -M parameter; this will start SQL Server in single user mode which is required to restore Master database

Step 4: Restore database using SQLCMD

This is it, you have successfully restore your master database!!!

Is it this simple? No, wait, there are few things we need to be careful with....

The above example have save you because below conditions are true:
  1. You have back up of your master database, or
  2. This server is fresh installation or
  3. there are no user databases or
  4. this server is not production box
If the above conditions were not true, you will have to perform below steps:
  1. Restore / Rebuild system databases
  2. Recreate all the Login that you have on your crashed server - backing up master db helps you here
  3. you will have to recreate all the jobs and SSIS/DTS Packages that you have - backing up MSDB database will save you
  4. similarly distribution database backup will help you if you have replication configured
Conclusion :  I wish that you have schedule maintenance plan / job to take full backup of your system databases i.e. Master, MSDB, and Distribution(if you have configured replication).
Disclaimer : The example used here is for illustration purpose only.

1/23/2012

Revamping SUG 2nd Meeting



Friends,
Last Saturday, 21st we have 2nd meeting of SUG members and this time we made progress – I, Vinay and Matang was present in meeting Smile .We have discussed following :
  1. We have decided that portal management will be done by I, Vinay and Matang initially, here are the module that we’ll be adding content on:
    1. Forums and Team section –> Hemantgiri S Goswami
    2. Article Section –> Matang Panchal
    3. Blog Section –> Vinay Pugalia
  2. We’ll design and use common PPT theme during all our presentations
  3. We’ll organize quize every quarter
  4. From next meet, 1 member will make presentation of 15 minutes; starting with myself
  5. We will try to accommodate as many as practical / self demos in initial (and, so on) events
  6. We would also create PPT / Demo repository that we have used during event
  7. Also, there will be a download section where we’ll share scripts/codes to download
  8. We will open a bank account to manage the fund we’ll receive from Sponsors

See you in next meeting will be on 11th February 2012
Venue : 406, Empire State Building, Nr. Udhana Darwaja
Time : 7 PM


Image source: http://pmtips.net/wp-content/uploads/2010/03/meaningful-meetings.jpg

-- Hemantgiri S. Goswami (http://www.sql-server-citation.com )

1/02/2012

Roles and Responsibilty of SQL Server DBA

  • What is a role of a DBA in an organization?
  • What are the daily activities of a DBA?
  • What shall I check on regular basis?
  • What all processes shall I automate ?
  • What are the precautions, I have to take additionally?

These are the common question being asked in-common on may forums, here is what my listing is

• Design and implement Disaster Recovery

• Design, development, upgrade and Migration of Database Server.

• Providing support and handling most critical situations in vast variety of database systems.

• Database Optimization / Query Performance Tuning.

• Design and implementation Automated Database & Application fail over server setup.

• Capacity Planning, Change Management and Admin. Documentation.

• Review of existing design and specifications of the system.

• Design and documentation of operational specifications of the system.

• Monitoring of the development process, in order to confirm optimum performance of the system.

• Preparation of standards and follow up rules for the back – end system, to ensure a fully secured and a robust system.

• Design and implementation of the logical & physical structure of the database.

• Monitoring of performance of database servers and providing tuning measures.

• Performing database / application wide query tuning operations.

Try automate every process that needs to be performed on daily basis and/or requires manual intervention.

--  Hemantgiri S. Goswami (http://www.sql-server-citation.com)

1/01/2012

Wishing you all a very Happy and Prosperous new year, may success comes to your doorstep
Image source : Top CNN News