Extreme-Advice: What is Cloud Computing ?

Well, I have received the question “What is SQL Azure?” many times in an
email and in IT events I go. I generally write blog about SQL Server
but I have not written anything about SQL Azure so far. Before I
actually answer What the SQL Azure is, I have to explain a small bit
about “Cloud” first.

To read complete article, click here.

Reference: Ritesh Shah

http://Extreme-Advice.com
http://www.sqlhub.com
Quick Learn

Note: Microsoft Books online is a default reference of all articles but examples and explanations

Extreme-Advice.com: Find Blocking in SQL Server and use it to send an alert

As a DBA, I am always interested to find whether blocking is going on, in my environment or not? How long blocking exists? Which are the queries/SPs creating blocking etc.

Blocking generally occurs when one SQL Server connection (user process or application process) places a lock on a table or a number of rows and a second connection attempts to read or modify the data under the lock by first connection. Depending on the type of the lock, this can cause the second connection to wait until the first connection releases its lock. A blocked connection waits indefinitely for the blocking connection to release its lock.

Read complete article here.

Extreme-Advice: Write process in TRASACTION LOG (.LDF) file in SQL Server

I have written one article about Transaction Log File (.LDF) yesterday, today I am presenting one more article on the same subject.

There is a myth going on in the mind of many developers that only DML statement like INSERT/ UPDATE & DELETE are being written in the log file but the truth is that SQL Server writes DDL operation like CREATE TABLE or CREATE INDEX etc. in the log file too.

Read complete article here:

 

Extreme-Advice: Transaction Log File (.LDF) in SQL Server along with ACID property and recover mode of database

SQL Server databases created with two types of file:

Data File (File with extension .MDF/.NDF)

Log File (File with extension .LDF)

Data File can be one or more than one but physical log file will always remain one for each database. You have control over the size of log file but you can’t have more than one physical log file. There are so many mysteries and myth roaming around log file in developer’s mind so I thought to take an initiative to break this ice.

Read complete article here:

Extreme-Advice: Find locked table name with duration and count in SQL Server

Finding LOCK table in SQL Server is one of essential task of DBA. Locked table for long time in SQL Server adversary affect on performance of the application, especially in pick business hours.

I have one SQL Server VIEW which help us to find all the table which are being locked currently along with duration since it is being locked.

Please read complete article here:

Book Review – SQL Server Interview Questions and Answers

Well, I am not as qualified in SQL Server as the authors ofthis book (Pinal Dave & Vinod Kumar) though I dare to writemy review for his book as both of the authors are in my favourite list and I don’teven miss any article written by them then how could I miss a book written bythem? After reading the book, I really tempted to share my personal opinion with my blog reader.
“SQL Server Interview Questions and Answer” makes firstimpression that this book is written to prepare you for the interview of DBA orSQL Developer or BI professional but NO, this book is not ONLY for those whoare preparing for an interview, even seasoned developer or DBA could refer thisbook to master the basics which we may avoid or forget over the time butknowing those may create a firm ground for the project we all are working on.
Both of these authors are well known to present hard &difficult concept in very simple yet powerful manner which directly executeINSERT command in your memory without any trigger or exception, just like straitthrown dart pinch in board, this really show very hard work of both authors.
I really impressed with the book for following points.
  • “Points to Ponder” section at the end of each chapter as a Quick references to Joes 2 Pros books (I had privilege to read few of them)
  • Very inspiring quote at the begging of chapters (I enjoy it in Vinod Kumar’s twits too, in twitter)
  • Links to SQLAuthorty’s articles
When I first heard about this book, I though how much morecontent could be there in this book? As Pinal has already written the seriesarticles on this topic but with my surprise, there are LOT MORE to learn inbook so even if you have read all articles on this series in Pinal’s blog, don’thesitate to have this book, you will have so many (80%) new stuffs to look at.
This book scores 10/10 and I personally highly recommend thisbook as a good & quick reference to any professional who are dealing withSQL Server at any level.
To order the copy of the book for your own, visit SQLAuthority.com
Happy Reading!!!
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles butexamples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com
Ask me any SQL Server related question at my “ASK Profile

Error Fix: Msg 605 Attempt to fetch logical page (3:1307866) in database 6 failed. It belongs to allocation unit 72057594113359872 not to 72057594113490944

Msg 605, Level 21, State 3, Line 1
Attempt to fetch logical page (3:1307866) in database 6failed. It belongs to allocation unit 72057594113359872 not to72057594113490944.
Or
Msg 21, Level 21, State 1, Line 1
Warning: Fatal error 605 occurred at OCT  31 2011 6:08AM. Note the error and time, and contact your system administrator.
This error comes in red color is disguise, if you login withany user which is not sysadmin type user, you will see this kind of error incorruption of page(s), if you login with SA, Administrator or and otherSysAdmin login, you will not see error comes in red color but the descriptiveerror given in the title
There was a festival holidays in our Indian office from 26thto 28th OCT 2011 (Wed/Friday) so obviously I was out of town andback after 5 days on 31st OCT 2011. As soon as I come to the officeand checked few of my email, I suddenly get complain that few pages in oursoftware are throwing an error so I picked up the query which was there inthose pages along with the same parameter they were providing and found theerror given above.
As soon as I read this error, I came to know that there is apage corruption in database.  It may bedue to heavy snow fall in NJ in October, they have got power failure there fromfew days and tried to keep the server up and running via power generator. Assoon as Power Generator’s fuel get finished, everything gets down and afterrefuel, they starts everything again. I came to know this as soon as I comeback from holiday. I think this is the Indian New Year gift to me.
I tried to gather some more information about the data fileand page number given in error message with DBCC PAGE command.
dbcc traceon(3604)
dbcc page(‘MyDatabaseName’,3,1307866,3)

dbcc traceoff(3604)

You can use option 0,1,2,3 as the last parameter (bold 3) ofDBCC PAGE command.
So now I have two options.
1.)    Restorethat page from full Database backup
2.)    TryDBCC commands and if needed, allow data loss
I HIGHLY RECOMMEND to go for 1st option but ifyou are out of luck and don’t have last full backup, you must have to go forsecond way.
I have restored page from my last full database backup withbelow given TSQL.
RESTORE DATABASE MyDatabaseName
PAGE = ‘3:1307866’
FROM DISK = ‘D:\MyDatabaseName.bak’
WITH NORECOVERY
Now, let us talk about second option if you don’t have fullbackup of your database. Use DBCC CHECKDB command.
–checkingdatabase’s integrity and won’t show so many informational message,
–it will onlyshows error messages and warnings.
DBCC CHECKDB(‘MyDatabaseName’) WITH NO_INFOMSGS
Once you execute above command, it will recommend you repairlevel. it may recommend REPAIR_REBUILD if you really lucky but if you will seerepair level REPAIR_ALLOW_DATA_LOSS, you have to be ready to lose some of yourdata.
You may use either of the below given command based on theRepair Level you have been suggested.
1.)
ALTER DATABASE MyDatabaseName SETSINGLE_USER
GO
DBCC CHECKDB(‘MyDatabaseName’, REPAIR_REBUILD)
GO
ALTER database MyDatabaseName SETMULTI_USER
GO
2.)
ALTER DATABASE MyDatabaseName SETSINGLE_USER
GO
DBCC CHECKDB(‘MyDatabaseName’, REPAIR_ALLOW_DATA_LOSS)
GO
ALTER database MyDatabaseName SETMULTI_USER
GO
Moral of the story is, always have FULL recovery model foryour database and schedule full/ transaction/ differential backup policy. Thisis a MUST DO for any DBAs. You never know, when will you need it!!!!
Reference: Ritesh Shah
 
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles but examplesand explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com
Ask me any SQL Serverrelated question at my “ASK Profile

Playing with OPTION KEEPFIXED PLAN hint in SQL Server

My previous article was on Compilation& Recompilation of Stored Procedure. After reading that article, two ofmy reader sent me an email about more clarification on some terminology and thatis the base of writing this article.
Actually SQL Server Query Optimizer is really one of thesmart tools which used to find or generate best execution plan for query or storedprocedure and make the task easy for DBA. Basically it uses Cost BasedOptimizer (CBO) to do this task, even sometime feels to have specific ExecutionPlan for query so Microsoft have provided many different hints at differentlevel.
Query Optimizer (QO) used to save execution plan when itcompiles Stored Procedure first time and use the same execution plan when thesame stored procedure is being used again so that you can get rid of overheadof generating execution plan again and again. 
When index statistics changes heavily, QO used to recompilethe statement to get best plan for your stored procedure but if you are surethat the existing Plan would works fine than one should go for OPTION KEEPFIXEDPLAN for that statement so that you can save your resources and boost upperformance.
I will demonstrate this with few queries run in SQL ServerManagement Studio (SSMS) and capture the results in Profiler. 
I will select following Events in Profiler while creatingnew Trace for my server.
Stored Procedure
  • SP:Completed
  • SP:Recompile
  • SP:smtpCompleted
  • SP:smtpStarting

 

Now execute following TSQL in your SSMS.
–create onedatabase which you can delete after running this example
create database SQLHub
GO
USE SQLHub
GO
–if orderstable is already there. you can delete it than create new one with name”Orders”
IF OBJECT_ID(‘orders’, ‘U’) IS NOT NULL BEGIN
      DROP TABLE orders
END
GO
–creating table
CREATE TABLE orders (OrderID INT IDENTITY, OrderDate DATETIME, Amount MONEY, Refno INT)
GO
–creatingnonclustered index
CREATE NONCLUSTERED INDEXIDX_ORD ON Orders(amount)
GO
–inserting only1 record in our table
INSERT INTO orders VALUES(GETDATE(),1001,111)
GO
–creating SPwhich will SELECT all records from Orders table where Amount is 1001
CREATE PROC spGet_ord
AS
SELECT * FROM orders WHERE Amount=1001
GO
–execute SP
exec spGet_ord
GO
If you will see in profiler than you would get followingevent captured



Now, make change in Index statistics by inserting so manyrecords in table so that we can test the effect in profiler after executing SPagain.
–inserting50000 fack rows into table
INSERT INTO orders (OrderDate, Amount, Refno)
SELECT TOP 50000
      DATEADD(minute, ABS(a.object_id % 50000 ), CAST(‘2010-02-01’ AS DATETIME)),
      ABS(a.object_id % 10),
      CAST(ABS(a.object_id) AS VARCHAR)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
GO
–execute SPagain
exec spGet_ord
GO

Now, if you see the profiler, you will see “SP:Recompile”event as your statistics are updated so it need recompilation of statement. If youagain few more thousands record in same table and execute the same SP again,you will see recompilation again.
Now, after droping table and SP, we will make one smallchange in Stored Procedure and will use “KEEPFIXED PLAN” hint so that we canavoid recompilation.
drop proc spGet_ord
GO
drop table orders
go
–creating table
CREATE TABLE orders (OrderID INT IDENTITY, OrderDate DATETIME, Amount MONEY, Refno INT)
GO
CREATE NONCLUSTERED INDEXIDX_ORD ON Orders(amount)
GO
INSERT INTO orders VALUES(GETDATE(),1001,111)
GO
CREATE PROC spGet_ord
AS
SELECT * FROM orders WHERE Amount=1001
–adding belowstatement other than that, same code as previous SP
OPTION (KEEPFIXED PLAN);
GO
exec spGet_ord
GO
After recreating table along with fresh records, we aregoing to see what happened while executing SP in above statement.

Since our table now has only 1 record so it is time tochange statistics with bulk insert as follows again.
–inserting100000 fack rows into table (BTW, thank to Jacob Sebastian, copy in INSERTscript from one of his demo to generate big table)
INSERT INTO orders (OrderDate, Amount, Refno)
SELECT TOP 50000
      DATEADD(minute, ABS(a.object_id % 50000 ), CAST(‘2010-02-01’ AS DATETIME)),
      ABS(a.object_id % 10),
      CAST(ABS(a.object_id) AS VARCHAR)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
GO
exec spGet_ord
GO
–if you wish,you can uncomment below code and delete SQLHub database
–use master
–go
–drop database sqlhub
Here is the screen capture of Profiler which doesn’t showRecompilation.

 

You can even add few more thousands of rows and execute SPagain, you won’t get recompilation. 
Reference: Ritesh Shah
 
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles butexamples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com
Ask me any SQL Server related question at my “ASK Profile



Playing with OPTION KEEPFIXED PLAN hint in SQL Server

My previous article was on Compilation& Recompilation of Stored Procedure. After reading that article, two ofmy reader sent me an email about more clarification on some terminology and thatis the base of writing this article.
Actually SQL Server Query Optimizer is really one of thesmart tools which used to find or generate best execution plan for query or storedprocedure and make the task easy for DBA. Basically it uses Cost BasedOptimizer (CBO) to do this task, even sometime feels to have specific ExecutionPlan for query so Microsoft have provided many different hints at differentlevel.
Query Optimizer (QO) used to save execution plan when itcompiles Stored Procedure first time and use the same execution plan when thesame stored procedure is being used again so that you can get rid of overheadof generating execution plan again and again.
When index statistics changes heavily, QO used to recompilethe statement to get best plan for your stored procedure but if you are surethat the existing Plan would works fine than one should go for OPTION KEEPFIXEDPLAN for that statement so that you can save your resources and boost upperformance.
I will demonstrate this with few queries run in SQL ServerManagement Studio (SSMS) and capture the results in Profiler.
I will select following Events in Profiler while creatingnew Trace for my server.
Stored Procedure
  • SP:Completed
  • SP:Recompile
  • SP:smtpCompleted
  • SP:smtpStarting

 

Now execute following TSQL in your SSMS.
–create onedatabase which you can delete after running this example
create database SQLHub
GO
USE SQLHub
GO
–if orderstable is already there. you can delete it than create new one with name”Orders”
IF OBJECT_ID(‘orders’, ‘U’) IS NOT NULL BEGIN
      DROP TABLE orders
END
GO
–creating table
CREATE TABLE orders(OrderID INT IDENTITY, OrderDate DATETIME, Amount MONEY, Refno INT)
GO
–creatingnonclustered index
CREATE NONCLUSTERED INDEXIDX_ORD ON Orders(amount)
GO
–inserting only1 record in our table
INSERT INTO orders VALUES(GETDATE(),1001,111)
GO
–creating SPwhich will SELECT all records from Orders table where Amount is 1001
CREATE PROC spGet_ord
AS
SELECT * FROM orders WHERE Amount=1001
GO
–execute SP
exec spGet_ord
GO
If you will see in profiler than you would get followingevent captured
Now, make change in Index statistics by inserting so manyrecords in table so that we can test the effect in profiler after executing SPagain.
–inserting50000 fack rows into table
INSERT INTO orders(OrderDate, Amount, Refno)
SELECT TOP 50000
      DATEADD(minute, ABS(a.object_id % 50000 ), CAST(‘2010-02-01’ AS DATETIME)),
      ABS(a.object_id % 10),
      CAST(ABS(a.object_id) AS VARCHAR)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
GO
–execute SPagain
exec spGet_ord
GO
Now, if you see the profiler, you will see “SP:Recompile”event as your statistics are updated so it need recompilation of statement. If youagain few more thousands record in same table and execute the same SP again,you will see recompilation again.
Now, after droping table and SP, we will make one smallchange in Stored Procedure and will use “KEEPFIXED PLAN” hint so that we canavoid recompilation.
drop proc spGet_ord
GO
drop table orders
go
–creating table
CREATE TABLE orders(OrderID INT IDENTITY, OrderDate DATETIME, Amount MONEY, Refno INT)
GO
CREATE NONCLUSTERED INDEXIDX_ORD ON Orders(amount)
GO
INSERT INTO orders VALUES(GETDATE(),1001,111)
GO
CREATE PROC spGet_ord
AS
SELECT * FROM orders WHERE Amount=1001
–adding belowstatement other than that, same code as previous SP
OPTION (KEEPFIXED PLAN);
GO
exec spGet_ord
GO
After recreating table along with fresh records, we aregoing to see what happened while executing SP in above statement.
Since our table now has only 1 record so it is time tochange statistics with bulk insert as follows again.
–inserting100000 fack rows into table (BTW, thank to Jacob Sebastian, copy in INSERTscript from one of his demo to generate big table)
INSERT INTO orders(OrderDate, Amount, Refno)
SELECT TOP 50000
      DATEADD(minute, ABS(a.object_id % 50000 ), CAST(‘2010-02-01’ AS DATETIME)),
      ABS(a.object_id % 10),
      CAST(ABS(a.object_id) AS VARCHAR)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
GO
exec spGet_ord
GO
–if you wish,you can uncomment below code and delete SQLHub database
–use master
–go
–drop database sqlhub
Here is the screen capture of Profiler which doesn’t showRecompilation.

 

You can even add few more thousands of rows and execute SPagain, you won’t get recompilation.
Reference: Ritesh Shah
 
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles butexamples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com
Ask me any SQL Server related question at my “ASK Profile

Some facts about Stored Procedure Compilation & Recompilation

I generally ask one question in interview “If we have onecomplex query which JOIN five table, what would work best from .NETapplication, Call of Query or Stored Procedure?” 80% of candidate used to say “SPworks fast”. My next question always would be “WHY?” than out of those 80%, 60%would say “Because SP is a compiled code”. After that I fire my follow upquestion, I can see option of “Compile page or project in .NET but I never seethat kind of option in SSMS, how do you compile your SP?”, once I EXECUTE thisquestion, 90% candidate of those 60% candidate would like to keep silence ordivert the talk.
Anyway, intention of this article is to let you know somefacts about SP compilation & Recompilation. Since it is big topic andwouldn’t cover under on article, I may come up with some more articles on thistopic but right now, let me explain some basic facts only.
First of all, let me tell you that you don’t need to compileStored Procedure manually, when you execute it, SQL Server will compile yourStored Procedure for you and save the execution plan for future use so that itdoesn’t need to compile again and again, this is generic understanding, itdoesn’t work all time as few facts are there which cause recompilation manytime or every time. If you want to recompile your Stored Procedure manually,you should use “SP_Recompile” Stored Procedure given by SQL Server.
Now, you think if recompilation is that bad than whyMicrosoft has given facility to recompile? Well, let me have an opportunity tobreak the ice, recompilation of stored procedure is not always bad. It may bebeneficial or may be harmful, it is totally depends on the situation.
Actually compilation of Stored Procedure stores theexecution plan first time you execute your Stored Procedure and every follow upcall would use the same execution plan but recompilation of SP would be helpfulif you have new statistics or new index on the table. BTW, in SQL Server 2008+there is in-built functionality to recompile at statement level rather thanrecompiling whole stored procedure which is less resource centric. 
Following is the list of basic cause which forces StoredProcedure to recompile.
·         
  • Change in SET option within Stored Procedure
  • Execution plan is very old
  • Schema change in table, index, view or temptables which are used in Stored Procedure
  •  “Deferred object resolution”, means object wasnot available while compiling Stored Procedure  but you have created later on,may be some temp table you have created in Stored Procedure.
  •  Call of “SP_Recompile” Stored Procedure.
  • Call of RECOMPILE clause in Stored Procedure.
  • Statistics are old
How to avoid Stored Procedure recompilations?
  • Avoid using temp table or other DDL statements as long aspossible.
  • Use table variable in Stored Procedure if needed
  • Avoid changing SET option in Stored Procedure likeARITHABORT, Quoted_Identifier, ANSI_NULLS, ANSI_WARNINGS etc.
  • Avoiding recompilation by statistics change by using “KEEPFIXEDPLAN” hint.
  • Disable Auto Update statistics for your database.
Well, these are very basic understanding and each point ofthis article may consume separate dedicated article and I may come up withseries on this very soon.
Reference: Ritesh Shah
http://www.sqlhub.com
Note: Microsoft Books online is a default reference of all articles butexamples and explanations prepared by Ritesh Shah, founder of
http://www.SQLHub.com
Ask me any SQL Server related question at my “ASK Profile