Here is a situation, i wanted to blog about. Renaming a database physical file. some may ask, why would anybody do it.  Well for the people who work like “alice in wonderland”, everything is streamlined without hiccups, but for a volatile environment like i work in anything is possible.  so back to the question of why would anybody rename the database, well there are certain situations as follows:

We will be taking the example of 2 databases ProjectDatabase_DEV and TEST as shown. one is a development database and the other is a test database as per the SDLC.

image

Developers working on limited resources use shared SQL Server environment and if the Project name has changed, so will be database name too, this is to streamline things a bit. When the objects are moved from _DEV to _TEST to production server, we have to take care of renaming and placing the database files appropriately:

Let us start with our databases: execute this command sp_helpdb ProjectDatabase_DEV

image

Now consider a scenario, where the team has decided to move this database into Production.

Steps you will take are take a most current full backup of the database and restore it on the production system.

(I am not going to talk about the users and logins and dbcc etc. this is just about renaming the db files)

Now we restore the database on the production server as ProjectDatabase.

There are  2 ways to restore the database : SSMS and T-SQL. I will use T-SQL for reference here:

Let us assume the database is restored to production using SSMS or T-SQL as

RESTORE database ProjectDatabase from disk = ‘C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\ProjectDatabase_DEV.bak’

Now check the database on production server with sp_helpdb ProjectDatabase

image

you see the database Logical name still contains the _DEV as well as the Physical File Name.

So what do we do here: Things are simple: using T-SQL we change the logical and physical names as follows:

ALTER DATABASE ProjectDatabase
MODIFY FILE (NAME=’ProjectDatabase_DEV’, NEWNAME=’ProjectDatabase’)

After you execute the above statement, run sp_helpdb again, and here is the Output (see the Logical Name has changed)

image

Now we will change the Physical File name on the right:

ALTER DATABASE ProjectDatabase
MODIFY FILE (NAME=’ProjectDatabase’, FILENAME=’C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\ProjectDatabase.mdf’)

Check again with sp_helpdb and here is the output (see the physical file name has change)

image

But the Physical file residing in the Data Folder have not changed: WHY?. This is because the database file name has been changed in the system tables and not the file itself.

image

After a couple of week of SQL Server running smoothly, the sysadmins re-started the Server and suddently no one was able to access the database anymore. sp_helpdb produced no results and gave permission error etc. This is how it looked:

image

no one was able to see the objects inside the database. Even if you try to check out the properties you see this:

image

so to correct this was to stop SQL Server Service. Rename the Physical mdf and ldf files to the required names as were defined previously. Then start the SQL Server service, and LO!, you are able to access the Database.

The best practise is to check the Files names and paths while getting the RESTORE done either using T-SQL as below or SSMS.

RESTORE Database ProjectDatabase from disk = ‘C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Backup\ProjectDatabase_DEV.bak’
WITH REPLACE, – This is Optional and is only required on existing databases.
MOVE ‘Logical MDF Name’ to ‘Path to Physical FileName’,
MOVE ‘Logical LDF Name’ to ‘Path to Physical FileName’

Lets talk about Migrating a single database from SQL 2000 to 2005/2008 and how easy it is. Here are some of the methods i used for the migration.

This Blog has 2 parts: The First will detail the Database Moving Strategies and Second will discuss the core strategies after the move, so the last part is not left un-read or hidden as it is a vital strategy.

Before we proceed to the examples, the things to remember are ":

  • SQL Server 2000/2005/2008 Compatibility Mode.
  • Database Physical Folder Location.
  • Jobs associated with the database.
  • Logins Associated with the Database.
  • Objects that reference this database(Stored Procedures / Functions etc.) 
  • Linked Servers ( if this database is reference in particular)
  • DTS Packages.
  • Analysis Services Tables Derived from the Database(if any).
  • Health of the Database itself. (We will talk about this later.)

These examples are good if you have the luxury of carrying on a Side by side installation (if you have separate Server for SQL 2005 and not upgrading the SQL Server 2000 to 2005 called in-place upgrade)

PROCEDURE 1:

Backup the database from source (SQL Server 2000) and restore the database Server 2005.

Either use SSMS/SSEM (Enterprise Manager as in SQL 2000) Or use T-SQL for the Backup and restore Process.

image

T-SQL goes something like this:

image 
Wow, T-SQL and how did i derive this T-SQL? This is how i did it from the Backup Up database Dialog box.

Script Action to Clipboard and then paste it in Query window

image

NOW, Let us do a Restore of the Database using either of the methods (SSMS or T-SQL)

For our convince i detached the pubs database with the procedure described below in the DEATCH Database Section.

image

In the Restore Database Dialog, Write the name of the database in “To database” and select From Device (if it is a file).  Click on the “From device” Browse button on the right.

image

Click Add button in the Specify Backup window.

image

Select the Database you want to restore. In this case we will select Pubs.bak

image

After select the pubs.bak file check the box named ‘”Restore”

image

click on Options to check for more interesting restore options.

image

If you are going to restore transaction Logs after the initial Full backup, you need to select the appropriate options. They speak for themselves and need not be mentioned in detail here.

I have checked the “Overwrite the Existing Database” as i might have a existing copy of the pubs database and this option asks SQL Server to overwrite it if required.

once you click on the OK button, the Database will be restored.

image

image

and using T-SQL is as simple as :

image

PROCEDURE 2:

Stop the SQL Server Service and move the .mdf and .ldf files to SQL Server 2005 Server.

There are couple of ways of Stopping the SQL Server service. Either through Start –> Administrative Tools –> Services:

image

or through SQL Server configuration Manager.

image

Once the service is Stopped, Copy the .mdf and .ldf of the required database to the desired location of the new server : (Example we will copy the pubs database from original location to some other folder in c: Drive.)

I have copied the pubs.mdf and ldf files up one folder. instead of mssql.1 it is in the MSSQL Folder.

Next Step is to attach the Database on the new server.

Right click on Server/Databases and click on Attach:

image

In the Attach Dialog, click Add and select the appropriate mdf file.

image

image

Click OK and the database is attached.

PROCEDURE 3:

Detach Database from SQL Server 2000 and Attach it on SQL Server 2005 Server.

image

 

image

The Attach procedure is already described above, so use that procedure.

Check out PART 2 for What to do after the Database has been moved.

I chalk out some difference between the ISNULL and COALESCE Keywords in SQL Server Engine.

You can Google around for more deep explanations, but consider this a starting point.

ISNULL – Propitiatory T-SQL function

COALESCE – ANSI SQL Compliant

ISNULL – Takes only 2 parameters [ISNULL (NULL, NULL) will return valid result as INT]

COALESCE – Takes variable Number of Parameters and requires some type definition to produce valid results as INT

Example: [COALESCE (NULL, NULL) will produce errors]

[COALESCE CAST (NULL as INT), NULL] will produce valid results.

ISNULL – will always return results as INT (converted to int when result is produced)

COALESCE – will have to provide some type as defined in the example above.

Both can produce Different QUERY PLANS, of which COALESCE produces the WORST PLAN, when used in sub-queries then ISNULL since COALESCE internally operates like a CASE Statement.

When writing Complex Joins and computed Columns, Pl pay close attention, if you are using ISNULL or COALESCE

I was working with a following scenario:

SQL Server 2005 Standard Edition SP3 on Windows 2003 SP2 Standard Edition.

Processors: 2 Socket (4 cores each)

Physical Memory on Box 8GB

 

But the SQL Server was not able to see all the 8GB.

It was however able to use all the 8 processors.

This is because of the limitations of the windows and SQL server editions.

So what do we do to make SQL Server see/use of all of the available physical memory.

I decided on upgrading the Windows STD edition to windows enterprise edition, which will make windows OS use/see all the available physical memory on the box.

And which in turn will help SQL server to use/see the available Memory that is available to Windows OS (or rather, SQL Server is able to use all the physical Memory that the windows OS see’s).

So, problem solved… SQL Server was able to use/see the available RAM and we could use the /PAE and or AWE to allocate the Memory Limits… (Also used the Locked pages in Memory setting)

So, our solution was a simple OS upgrade.

 

Some handy links.

Check out this Memory Limits for Windows Editions link.

Check out more details about the SQL Server 2008 Pricing and Editions here

SQL Server 2005 Editions comparison for features here

 

Here are the Step that are followed by the SQL Server Restore Process

RestoreDatabase: Database MANI_TESTDB2000
RestoreDatabase: Streams open
RestoreDatabase: Configuration section loaded
Starting up database ‘MANI_TESTDB2000′.
RestoreDatabase: Planning completed
RestoreDatabase: Creating files
RestoreDatabase: File creation completed
RestoreDatabase: Restoring backup set
RestoreDatabase: Backup set restored
Starting up database ‘MANI_TESTDB2000′.
Bypassing recovery for database ‘MANI_TESTDB2000′ because it is marked IN LOAD.
Starting up database ‘MANI_TESTDB2000′.
Bypassing recovery for database ‘MANI_TESTDB2000′ because it is marked IN LOAD.
Recovery is checkpointing database ‘MANI_TESTDB2000′ (5)
RestoreDatabase: Done with fixups
Starting up database ‘MANI_TESTDB2000′.
Analysis of database ‘MANI_TESTDB2000′ (5) is 100% complete (approximately 0 more seconds)
RestoreDatabase: Writing history records
Database restored: Database: MANI_TESTDB2000, creation date(time): 2004/11/13(13:37:49), first LSN: 146029:1710:1, last LSN: 146029:6464:1, number of dump MANI_TESTDB2000ices: 1, MANI_TESTDB2000ice information: (FILE=1, TYPE=DISK: {‘E:\MSSQL7\BACKUP\DB.Backups\Prod_db_200901020045.BAK’}).
RestoreDatabase: Finished

These are all the crucial Steps the restore process taken to restore a database and then initialized it. this information is stored as usual in SQL SERVER ERROR LOG.

This was for SQL 2000 version: use can use DBCC TRACEON(3004, 3605, -1) to tun on the database restore logging into the SQL Server Error Log and use DBCC TRACEOFF(3004, 3605, -1) to turn the logging process off.

A Users Group meeting a Pittsburgh ended up with some basic questions bowled at me and here is the roundup of the explanation :

Question 1: how can we check that for how long SQL Server has been running?
ANSWER: Several ways to check how long SQL Server has been running or to REPHRASE this Question: When was SQL Server last restarted.
In Windows–> Administrative Tools–>Event Viewer look for SQL Server Restart info.Run a query in analyzer (Select * from master..sysprocesses where spid=1)This is the first system ID which logs into the SQL Server, after the SQL has been restarted.Mind it, the login_time will be off by a Few minutes vs. the Event Viewer, which will anyway show you the exact time the SQL server Started.
OR Check the SQL Server Error Log and see the DATE for the first logged Event in the Error Log, this should match with the Event Viewer and should be the time When SQL Server was Started.But again: SQL Server Error Log can be Recycled without Restarting SQL Server, So will need a Proper analysis, based on the above Theories.

Question 2: How to monitor Database Corruption using DBCC logs and what they actually mean?
ANSWER: Lengthy Answer and discussion, but in short….Command used to Check Database Consistency Check and are set of Database Console Command(s)DBCC CHECKDB ()Check for syntax and more on SQL Server Books Online.
This will Read through The internal Structure of the Database and Report for corruptions in Pages and Extents.
The Result set should be something like this:CHECKDB found 0 allocation errors and 0 consistency errors in database.
The Problem Statement for CHECKDB goes something like this: CHECKDB needs a consistent view of the database Why does it need a consistent view? Because, usually its running on a live database(s) with all kinds of things going on. we need to read and analyze the complete database but it can’t do it immediately and instantaneously, so it has to take a diff approach and to make sure it what it reads is transactionally consistent.
From SQL 2000, the DBCC is a online operation, which even reads through to Log to make sure it did not miss anything.
I will Skip to Fast Facts here:
DBCC Does various internal Database Allocation(pages and Extents) Checks and Chains (Index allocation maps etc)
A Full CHECKDB on the DATABSE will do a Lot of Stuff and will require more time to complete on a ONLINE DB and a Big DB.
So there are other options you should try and the best one is DBCC CHECKDB () WITH PHYSICAL_ONLY .
This is greatly Reduce the Time it takes to run the command and also REDUCE the SURFACE SCAN of the DATABASE to IMP INTERNAL STRUCTURE ONLY.(ALLOCATION MAPS ETC..)

Question 3: Why do you need to backup the Database to TRUNCATE the LOG and how do you Truncate the LOG.
ANSWER: By Backing up the Database, you Virtually Backup the last available Transaction along with the Database. So you have a Transaction log backup also if you do a FULL Backup. Then you can Truncate the LOG, to minimize the Transaction LOSS.Here is the Syntax and Explanation of how this can be DONE:
Do a Regular Full backup from EM(Enterprise Manager) or SSMS(SQL Server Management Studio)then check for available space in the Database files with this Query to see if there is space available in LOG File that could be shrunk etc.
SELECT name ,size/128.0 – CAST(FILEPROPERTY(name, ‘SpaceUsed’) AS int)/128.0 AS AvailableSpaceInMB_Files FROM sys.database_files
USE []DBCC SHRINKFILE (N” , 0, TRUNCATEONLY)–how to find the Database log File name [] USE [ADTTRC] select name,filename from sysfiles–and copy the log file name from name column
Or Change the RECOVERY MODEL to SIMPLE then run the Truncate Command.or right click Database Name–> Tasks–>Shrink–>Files
I hope i answered some basic questions to their satisfaction.

© 2010 D B A N A T I O N Suffusion WordPress theme by Sayontan Sinha
Better Tag Cloud