Sunday, November 4, 2012

SQL SERVER – Function to Round Up Time to Nearest Minutes Interval

Though I have written more than 2300 blog posts, I always find things which I have not covered earlier in this blog post. Recently I was asked if I have written a function which rounds up or down the time based on the minute interval passed to it. Well, not earlier but it is here today.
Here is a very simple example of how one can do the same.
CREATE FUNCTION [dbo].[RoundTime] (@Time DATETIME, @RoundToMin INT)RETURNS DATETIME
AS
BEGIN
RETURN
ROUND(CAST(CAST(CONVERT(VARCHAR,@Time,121) AS DATETIME) AS FLOAT) * (1440/@RoundToMin),0)/(1440/@RoundToMin)ENDGO
Above function needs two values. 1) The time which needs to be rounded up or down. 2) Time in minutes (the value passed here should be between 0 and 60 – if the value is incorrect the results will be incorrect.) Above function can be enhanced by adding functionalities like a) Validation of the parameters passed b) Accepting values like Quarter Hour, Half Hour etc.
Here are few sample examples.
SELECT dbo.roundtime('17:29',30)SELECT dbo.roundtime(GETDATE(),5)SELECT dbo.roundtime('2012-11-02 07:27:07.000',15)
When you run above code, it will return following results.
Well, do you have any other way to achieve the same result? If yes, do share it here and I will be glad to share it on blog with due credit.
Reference: Pinal Dave (http://blog.sqlauthority.com)

How many replicas are maintained for each SQL Azure database?


For each database, three replicas are maintained for each database that one provision. One of them is primary replica. All read/write happen on primary replica and other replicas are kept in sync with primary replica. If for some reason, primary goes down, other replica is promoted to primary. All this happens under the hood.

(Read more here
http://bit.ly/sql-interview)

How can I Get Data from a Database on Another Server?


If you want to import data only through T-SQL query, then use OPENDATASOURCE function. To repeatedly get data from another server, create a linked server and then use the OPENQUERY function or use 4-part naming. If you are not adhered with T-SQL, then it is better to use import/export wizard, and you can save it as a SSIS package for future use.

(Read more here
http://bit.ly/sql-interview)

How to get @@error and @@rowcount at the same time?


If @@Rowcount is checked after Error checking statement then it will have 0 as the value of @@Recordcount as it would have been reset.
And if @@Recordcount is checked before the error-checking statement then @@Error would get reset. To get @@error and @@rowcount at the same time do both in same statement and store them in local variable. SELECT @RC = @@ROWCOUNT, @ER = @@ERROR

Read more here
http://bit.ly/sql-interview)

Thursday, November 1, 2012

What are the properties of the Relational tables?


What are the properties of the Relational tables?

Relational tables have six properties:

Values are atomic.
...
Column values are of the same kind.
Each row is unique.
The sequence of columns is insignificant.
The sequence of rows is insignificant.
Each column must have a unique name.

(Read more here http://bit.ly/sql-interview)

SQL SERVER – SHRINKDATABASE For Every Database in the SQL Server

I was recently called to attend the Query Tuning Project. I had a very interesting experience in this event. I would like to share to you what actually happened.
Note: If you are just going to say that shrinking database is bad, I agree with you and that is the main point of this blog post. Please read the whole blog post first.
The problem definition of the consultation was to improve the performance of the database server. I usually fly to the client’s location a day before, so the next day I am all fresh upon reaching the client’s office after a relaxing night’s sleep. Due to a fair availability of the flight, I reached the location earlier that day, at around 2 PM. I headed to the client’s location to familiarize myself with the place. I met the resident DBA and we talked for a few minutes. We looked at the index fragmentation during our conversation. It was the heaviest fragmentation that I have ever seen in my life. I asked the DBA if he could rebuild or reorganize indexes. He replied that he has never done it in the past one year. One year is really a long time; I could not believe that they have no maintenance task scheduled. I even wondered how they managed without index maintenance for the entire year. Anyway, I quickly handed my index script over him.
We waited until the end of their business hours, at about 5PM. After this, there are hardly any activities in the database. We executed the task on their production server after checking a few settings. The script ran for about 1.5 hours until it is finished. Afterwards, I checked the fragmentation of the indexes; it was very descent. In fact, some of the large tables were showing the fragmentation near to zero. I was pleased with this while the DBA confirmed that few reports even ran faster than before. Satisfied with the work done on Day 0, I left the location and went to the hotel where I stayed.
When I arrived to the location the next day, I had a meeting with the company director. He mentioned that he was updated by Dr. DBA regarding my de-fragmentation of indexes, and he wanted to see the status of the indexes. I ran my script once again to check the fragmentation of index. To my surprise, it was just like yesterday. I got confused and speechless. I checked the server instances and a few other things, but still nothing. The Sr. DBA also had no explanation at all. He started to mumble something I did not understand. Well, to make the long story short, I had a long face and did not feel comfortable. I was pretty sure that I had run the script of de-fragmentation and it worked fine.
Before I continued, I tried to check all the existing stored procedures and jobs. Finally, just like magic, I found the following code.
Before running the following code. Read the whole blog post.
EXEC sp_MSForEachDB 'DBCC SHRINKDATABASE (''?'' , 0)'
This code shrinks the whole database on a single SQL Server Instance. I instantly figured out where this code was used, and then I removed it. After I got rid of the code, I rebuilt and reorganized indexes. For the next 5 days, I faced no problem at all. Well, this is another reason not to shrink the database. Shrinking the database causes heavy fragmentation of the tables and reduces the performance. After shrinking, it seems that rebuilding indexes is necessary. But again, there should not be any real need to shrink the database. Do NOT shrink your database.
Reference: Pinal Dave (http://blog.sqlauthority.com), Image source unknown.

What is Isolation Levels?


What is Isolation Levels?

Transactions specify an isolation level that defines the degree to which one transaction must be isolated from resource or data modifications made by other transactions. Isolation levels are described in terms of which concurrency side-effects, such as dirty reads or phantom reads, are allowed.

Transaction isolation levels control:
...

Whether locks are taken when data is read, and what type of locks are requested.

How long the read locks are held.

Whether a read operation referencing rows modified by another transaction:

Blocks until the exclusive lock on the row is freed.

Retrieves the committed version of the row that existed at the time the statement or transaction started.

Reads the uncommitted data modification.

(Read More Here http://bit.ly/sql-interview)