How to Convert Seconds to HH:MM:SS

If you have a column that contains time in seconds and want to convert it to an hour : minute: seconds format, use this query. This query also takes care of displaying hours > 23.

DECLARE @SecondsToConvert int
SET @SecondsToConvert = 10000

-- Declare variables
DECLARE @Hours int
DECLARE @Minutes int
DECLARE @Seconds int
DECLARE @Time datetime

-- Set the calculations for hour, minute and second
SET @Hours = @SecondsToConvert/3600
SET @Minutes = (@SecondsToConvert % 3600) / 60
SET @Seconds = @SecondsToConvert % 60

-- Store the datetime information retrieved in the @Time variable
RTRIM(CONVERT(char(8), @Hours) ) + ':' +
CONVERT(char(2), @Minutes) + ':' +
CONVERT(char(2), @Seconds));

-- Display the @Time variable in the format of HH:MM:SS
SELECT CONVERT(varchar(8),CONVERT(datetime,@Time),108)

Find Last Day Of a Month in SQL Server 2005

Let us see how to find out the last day of a month :

-- Return Last Date of a Month
DECLARE @Month smallint
SET @Month = 1
SELECT DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1) as LastDateOfMonth,
DAY(DATEADD(Month, DATEDIFF(Month,0,getdate())+@Month, -1)) as LastDayOfMonth

The @Month accepts the month that needs to be added as the third parameter of the DATEADD function. You can set different values as shown below to view the last day of the month

1 - Current Month
0 - Last Month
2 - Next Month

View the Windows Logins and Groups in SQL Server 2005

You can retrieve permission and role information about a user from sql server's catalog views. The sys.server_principals lists the sql logins and groups having access to Sql Server. Let us see how to retrieve information using this view.

To find out all the Sql logins and groups

SELECT [name] as PrincipalName, type as PrincipalType, type_desc as TypeDescription, create_date as CreationDate,
modify_date as ModificationDate
FROM sys.server_principals
ORDER BY type_desc

To find out only the Windows login and groups

SELECT [name] as PrincipalName, type as PrincipalType, type_desc as TypeDescription, create_date as CreationDate,
modify_date as ModificationDate
FROM sys.server_principals
ORDER BY type_desc

The different type of Principal Types are :
S = SQL login
U = Windows login
G = Windows group
R = Server role
C = Login mapped to a certificate
K = Login mapped to an asymmetric key

References :

How to find out the views created on a table in SQL Server 2005

In order to find out the views created on a table, you can use the Information Schema Views. This is one of the several methods that SQL Server 2005 provides for obtaining metadata.

According to the BOL, the Information_Schema.View_Table_Usage "Contains one row for each table, in the current database, used in a view" . Let us see how to use it to find out the views on a given table:


SELECT VIEW_NAME FROM information_schema.view_table_usage
WHERE table_name = 'Categories'

returns you the view names on the table Categories.

Note: information schema view returns information about the objects to which the current user has permissions.

Recursive Common Table Expression

Common Table Expression (CTE) as you know is a temporary result set defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. If you are new to CTE's, read the BOL over here.

In this sample, we will see how to use Recursive CTE's to find out the Grade/Band of an employee in a company.

Case Scenario : We have a table called Employees. We need to display the Grade/Band of each Employee in the company. The Grade will be determined by the hierarchy of Managers above the person.
For the sake of demonstrating CTE's, we will create the following columns in the Employees table - ID, EName, Designation and ManagerID. Using recursive CTE, we will then display the Grade of each employee in the company. Grade 1 is the highest grade, given only to those who do not have managers above them.


-- create temporary table called Employees
ID int Identity(1,1) PRIMARY KEY,
EName varchar(50),
Designation varchar(50),
ManagerID int NULL

-- Insert some sample records in the Employees table
INSERT INTO #Employees VALUES('Paul','ED',NULL);
INSERT INTO #Employees VALUES('Goldman','CTO',1);
INSERT INTO #Employees VALUES('Jeniffer','VP Technology',1);
INSERT INTO #Employees VALUES('Sally','VP Sales',2);
INSERT INTO #Employees VALUES('Jack','VP Marketing',2);
INSERT INTO #Employees VALUES('Maner','Tech Head',4);
INSERT INTO #Employees VALUES('Jaidy','Sales Head',5);
INSERT INTO #Employees VALUES('Parry','Marketing Head',6);
INSERT INTO #Employees VALUES('Roger','Developer',7);
INSERT INTO #Employees VALUES('Yuan','Developer',7);
SELECT * FROM #Employees;

-- Use Recursive CTE to find out the Grade of each employee
WITH CTE(ID, EmployeeName, Designation, ManagerID, Grade)
SELECT ID, Ename, Designation, ManagerID, 1 as Grade
From #Employees WHERE ManagerID is NULL
SELECT e.ID, e.Ename, e.Designation, e.ManagerID, c.Grade + 1
FROM #Employees e
ON e.ManagerID = c.ID
SELECT ID, EmployeeName, Designation, ManagerID, Grade

How to see active connections for each Database in SQL Server 2005

At times, we need to check the number of active connections for each Database on our server. This can be done easily using the following script. The script displays the DatabaseName, the number of connections and the login name :

SELECT db_name(dbid) as DatabaseName, count(dbid) as NoOfConnections,
loginame as LoginName
FROM sys.sysprocesses
WHERE dbid > 0
GROUP BY dbid, loginame

How to extract Year, Month, Day, Hour, Minute and Seconds from a DateTime

I recently saw a post in the forums where a user wanted to extract the Year, Month, Day, Hour, Minute and Seconds from a DateTime field. Let us see how easily we can do it using the DATEPART() function. The DATEPART function accepts two parameters :

DATEPART ( datepart , date ) where
datepart - specifies the part of the date to return. For eg: year, month and so on
date - is the datetime or smalldatetime value


DATEPART(year, GETDATE()) as 'Year',
DATEPART(month,GETDATE()) as 'Month',
DATEPART(day,GETDATE()) as 'Day',
DATEPART(week,GETDATE()) as 'Week',
DATEPART(hour,GETDATE()) as 'Hour',
DATEPART(minute,GETDATE()) as 'Minute',
DATEPART(second,GETDATE()) as 'Seconds',
DATEPART(millisecond,GETDATE()) as 'MilliSeconds'

Note: When using a smalldatetime, only information up to the 'minute' gets displayed. Seconds and milliseconds are always 0.

Display Non-Null Values Even If A Column Contains Null

Our tables can contain NULL values if the columns allows them. However while displaying the data to the customers, we often have to display non-null values even if a column contains null. Let us see how to do that :


CREATE TABLE #Customers (id integer, cname varchar(20), pincode int)


INSERT INTO #Customers VALUES (1, 'Jack',45454 )
INSERT INTO #Customers VALUES (2, 'Jill', 43453)
INSERT INTO #Customers VALUES (3, 'Tom', 43453)
INSERT INTO #Customers VALUES (4, 'Kathy', null)
INSERT INTO #Customers VALUES (5, 'David', 65443)
INSERT INTO #Customers VALUES (6, 'Kathy', null)
INSERT INTO #Customers VALUES (7, 'Kim', 65443)


SELECT ID, cname, COALESCE(pincode,0) as pincode FROM #Customers

As you observe, COALESCE is used which returns the first nonnull expression among its arguments. So if the pincode is null, it returns the first nonnull expression, i.e 0.

How to Concatenate Column Values in SQL Server 2005

At times, we need to concatenate the values of columns and present it to the user. Let us see how to Concatenate Column Values in SQL Server 2005, espcially when one column is a varchar and the other is an integer.

-- SCRIPT To Create Table

CREATE TABLE #Customers (id integer, cname varchar(20), pincode int)

-- INSERT sample rows

INSERT INTO #Customers VALUES (1, 'Jack',45454 )
INSERT INTO #Customers VALUES (2, 'Jill', 43453)
INSERT INTO #Customers VALUES (3, 'Tom', 43453)
INSERT INTO #Customers VALUES (4, 'Kathy', 34544)
INSERT INTO #Customers VALUES (5, 'David', 65443)
INSERT INTO #Customers VALUES (6, 'Kathy', 65445)
INSERT INTO #Customers VALUES (7, 'Kim', 65443)

-- Concatenate Values

SELECT ID, 'Employee ' + cname + ' has a pincode ' + CAST(pincode as varchar(8)) as Info
FROM #Customers

How To Return Random Records From A Table

Let us see how to return random 'n' records from a table


CREATE TABLE #Customers (id integer, cname varchar(20), pincode int)


INSERT INTO #Customers VALUES (1, 'Jack',45454 )
INSERT INTO #Customers VALUES (2, 'Jill', 43453)
INSERT INTO #Customers VALUES (3, 'Tom', 43453)
INSERT INTO #Customers VALUES (4, 'Kathy', 223434)
INSERT INTO #Customers VALUES (5, 'David', 65443)
INSERT INTO #Customers VALUES (6, 'Kathy', 456556)
INSERT INTO #Customers VALUES (7, 'Kim', 65443)

-- Return 3 random records from the #Customers table

SELECT TOP 3 cname,pincode FROM #Customers ORDER BY NEWID()

So what happens over here is that the NEWID() is used to generate a unique value of type uniqueidentifier. So ordering the results by this ID every time gives us random rows. Cool!!

Understanding Authentication and Authentication Mode in Sql Server 2005

There is a difference between 'Authentication' and 'Authentication mode' in SQL Server 2005.

Authentication (2 types) - Windows and SQL Server Authentication.

Authentication mode (2 types) - Windows Authentication mode and Mixed Mode.

When using 'Windows authentication mode' you can only use Windows authentication to connect to SQL Server. When using 'Mixed mode' you can use either 'Windows authentication' or 'SQL Server authentication' to connect to SQL Server 2005

When to use what?

'Windows Authentication Mode' is much more secure than Mixed Mode. Windows Authentication utilizes Kerberos security protocol. Remember that in a typical installation, Windows Authentication is the default security mode. So when a user having a Windows user account connects to SQL Server, the server validates the account credentials using information in the Windows operating system.

SQL Server Authentication is provided for backward compatibility only. Whenever possible, use Windows Authentication.

If all the users users accessing the database are Microsoft Windows users, use 'Windows authentication mode' . If your environment consists of Windows users and Non-Windows users use 'Mixed mode'.

Copy a table from one database to another in SQL Server 2005

If you have a table in a database and you would like to copy the table to another database, use this query:

SELECT * INTO AdventureWorks.dbo.CustomersTemp FROM Northwind.dbo.Customers

Just remember that using this query will only transfer the schema and data. It does not transfer the indexes, foreign keys, statistics etc.

If you want to transfer all the objects from one database to another, open Sql Server Management Studio > Right click on your database > All Tasks > Generate SQL Scripts. Then run these scripts against the new database.

Transfer both schema and data

To copy both data and schema, use the Microsoft SQL Server Database Publishing Wizard 1.1. This tool works for both SQL 2000 and SQL 2005 and generates a single SQL script file which can be used to recreate a database (both schema and data).

How to quickly analyze a slow running query using SHOWPLAN_TEXT

To quickly analyze a slow-running query, examine the query execution plan to determine what is causing the problem.

SET SHOWPLAN_TEXT causes SQL Server to return detailed information about how the statements are executed.


USE Northwind;
FROM Customers
WHERE CustomerID = 'ALFKI';

Displays how indexes are used:
--Clustered Index Seek(OBJECT:([Northwind].[dbo].[Customers].[PK_Customers]), SEEK:([Northwind].[dbo].[Customers].[CustomerID]=CONVERT_IMPLICIT(nvarchar(4000),[@1],0)) ORDERED FORWARD)

Some Important Points :

1. SET SHOWPLAN_TEXT cannot be specified when using a stored procedure

2. You need to have the SHOWPLAN permission while running SET SHOWPLAN_TEXT

Read more about it over here

How to set up your database for Distributed queries

SQL Server 2005 provides you with the sp_addlinkedserver procedure. This proc creates a linked server to fire distributed queries against OLE DB data sources.

Let us see how to create a linked server against different data sources

Link to SQL Server 2005

EXEC sp_addlinkedserver
@srvproduct='SQL Server',

where @server is the name of the linked server; @srvproduct is the OLEDB Data Source to add (can be kept blank for SQL Server); @provider is the OLE DB provider that corresponds to the data source; @datasrc is the data source

Link to Access

EXEC sp_addlinkedserver
@server = 'SecondLS',
@provider = 'Microsoft.Jet.OLEDB.4.0',
@srvproduct = 'Access 2003',
@datasrc = 'C:\Data\MyData.mdb

Link to Excel

EXEC sp_addlinkedserver 'ThirdLS', 'Excel', 'Microsoft.Jet.OLEDB.4.0', 'c:\Data\MySheet.xls', NULL, 'Excel 5.0

Link to Oracle

EXEC sp_addlinkedserver
@server = 'FourthLS',
@srvproduct = 'Oracle',
@provider = 'MSDAORA',
@datasrc = 'Server1'

Check if a user has access to a database in Sql Server 2005

HAS_DBACCESS returns information about whether the user has access to the specified database (BOL).




1 if the user has access to the database
0 if the user does not have access to the database
NULL if the database does not exist

Find all databases that the current user has access to

SELECT [Name] as DatabaseName from master.dbo.sysdatabases

This query was written by a guy named safigi in sqlteamforums.

Passing parameter to the TOP clause

The TOP clause in SQL Server 2005 has been enhanced. You can now specify an expression as the number definition in the TOP clause. This makes your TOP clause dynamic as you can pass the number value in a variable and use that variable in the TOP clause of your T-Sql query

Sample Usage:

DECLARE @TopVar AS int
SET @TopVar = 20

CustomerID,CompanyName, ContactName
FROM Northwind.dbo.Customers

Execute a T-SQL statement at a given time

The 'WAITFOR' command is used to delay the execution of a batch, stored procedure or transaction till a specified time duration or till an actual time. Let me demonstrate this:

Create a DELAY for a specific amount of time

WAITFOR DELAY '00:01:00'
SELECT CustomerID, CompanyName, ContactName FROM CUSTOMERS

Delays the execution of the T-Sql statement by 1 minute. To delay by an hour, you would use '01:00:00'. You can specify a maximum of 24 hours.

Execute at the given time (actual time)

WAITFOR TIME '11:23:00'
SELECT CustomerID, CompanyName, ContactName FROM CUSTOMERS

Delays the execution of the T-Sql statement till the time '11:23 A.M'. You cannot specify a date, only time is allowed.

Using CASE function to evaluate one or more conditions

As mentioned in the BOL 'CASE Function evaluates a list of conditions and returns one of multiple possible result expressions'. In short CASE function returns a value by evaluating the expression given to it.

Let us see how we can add another column called 'Continent' to the Customers table of the Northwind database. We will be using the CASE function to evaluate the 'Continent' by giving the Country list as the expression.

SELECT CustomerID, CompanyName,Country, Continent =
WHEN COUNTRY IN ('Austria','Belgium','Denmark','Finland','France','Germany',
'Ireland','Italy','Norway','Poland','Portugal','Spain','Sweden','Switzerland','UK') THEN 'Europe'
WHEN COUNTRY IN ('Argentina','Brazil','Venezuela') THEN 'SouthAmerica'
WHEN COUNTRY IN ('Canada','Belgium','Mexico','USA') THEN 'NorthAmerica'

Once you run this query, you will find that the continent column gets displayed based on the WHEN expression using the CASE function