student Box Office

Learn more from here.

student Box Office

We will prepare the best articles for you to acquire knowledge.

student Box Office

We will help you always. Just follow our guidelines.

student Box Office

Come and join here to share the knowledge in latest Technologies.

student Box Office

Share your views with us. And update your knowledge.

Showing posts with label SQL functions. Show all posts
Showing posts with label SQL functions. Show all posts

Nov 21, 2011

Formatting number to add leading zeros - SQL Server

Formatting numbers to add leading zeros can be done in SQL Server. It is just simple. Lets create a new table and see how it works:

CREATE TABLE Numbers(Num INT);

Table Created.

Lets insert few values and see:


    INSERT Numbers VALUES('8');
    INSERT Numbers VALUES('9');
    INSERT Numbers VALUES('10');
    INSERT Numbers VALUES('11');
    INSERT Numbers VALUES('12');

SELECT * FROM Numbers;

1 row(s) affected.
1 row(s) affected.
1 row(s) affected.
1 row(s) affected.
1 row(s) affected.

Now we can see how the numbers are formatted with 4 digits, if it has less than 4 digits it will add leading zeros.
Data:

SELECT * FROM Numbers;


Num
8
9
10
11
12

5 row(s) affected.

Formatting:
SELECT RIGHT('0000'+ CONVERT(VARCHAR,Num),4) AS NUM FROM Numbers;

Num
0008
0009
0010
0011
0012

5 row(s) affected.

Oct 22, 2011

SQL SERVER – DATEDIFF – Accuracy of Various Dateparts


In SQL statement below the time difference between two given dates is 3 sec, but when checked in terms of Min it says 1 Min (whereas the actual min is 0.05Min)
SELECT DATEDIFF(MI,'2011-10-14 02:18:58' , '2011-10-14 02:19:01') ASMIN_DIFF

Is this is a BUG in SQL Server ?”
Answer is NO.
It is not a bug; it is a feature that works like that. Let us understand that in a bit more detail. When you instruct SQL Server to find the time difference in minutes, it just looks at the minute section only and completely ignores hour, second, millisecond, etc. So in terms of difference in minutes, it is indeed 1.
The following will also clear how DATEDIFF works:
SELECT DATEDIFF(YEAR,'2011-12-31 23:59:59' , '2012-01-01 00:00:00') ASYEAR_DIFF
The difference between the above dates is just 1 second, but in terms of year difference it shows 1.
If you want to have accuracy in seconds, you need to use a different approach. In the first example, the accurate method is to find the number of seconds first and then divide it by 60 to convert it to minutes.
SELECT DATEDIFF(second,'2011-10-14 02:18:58' , '2011-10-14 02:19:01')/60.0 AS MIN_DIFF
Even though the concept is very simple it is always a good idea to refresh it. 

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More