Tag Archives: Sql

Difference Between Temporary Table and Table Variable in Sql Server

This is the first article in the series of articles on Difference Between Temporary Table and Table Variable. This article lists out difference between Temporary Table and Table Variable.

Below is the complete list of articles in this series:

Difference Between Temporary Table and Table Variable – Summary

Both Temporary Tables (a.k.a # Tables) and Table Variables (a.k.a @ Tables) in Sql Server provide a mechanism for Temporary holding/storage of the result-set for further processing.

Below table lists out some of the major difference between Temporary Table and Table Variable. Each of these differences are explained in-detail with extensive list of examples in the next articles in this series which are listed above.

1. SYNTAX

Below is the sample example of Creating a Temporary Table, Inserting records into it, retrieving the rows from it and then finally dropping the created Temporary Table.

-- Create Temporary Table
CREATE TABLE #Customer 
(Id INT, Name VARCHAR(50))
--Insert Two records
INSERT INTO #Customer
VALUES(1,'Basavaraj') 
INSERT INTO #Customer 
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM #Customer
--DROP Temporary Table
DROP TABLE #Customer
GO

 

Below is the sample example of Declaring a Table Variable, Inserting records into it and retrieving the rows from it.

-- Create Table Variable
DECLARE @Customer TABLE
(
 Id INT,
 Name VARCHAR(50)   
)
--Insert Two records
INSERT INTO @Customer 
VALUES(1,'Basavaraj') 
INSERT INTO @Customer 
VALUES(2,'Kalpana')
--Reterive the records
SELECT * FROM @Customer
GO

RESULT:

2. MODIFYING STRUCTURE

Temporary Table structure can be changed after it’s creation it implies we can use DDL statements ALTER, CREATE, DROP.
Below script creates a Temporary Table #Customer, adds Address column to it and finally the Temporary Table is dropped.

--Create Temporary Table
CREATE TABLE #Customer
(Id INT, Name VARCHAR(50))
GO
--Add Address Column
ALTER TABLE #Customer 
ADD Address VARCHAR(400)
GO
--DROP Temporary Table
DROP TABLE #Customer
GO
Table Variables doesn’t support DDL statements like ALTER, CREATE, DROP etc, implies we can’t modify the structure of Table variable nor we can drop it explicitly.
3. STORAGE LOCATION
One of the most common MYTH about Temporary Table & Table Variable is that: Temporary Tables are created in TempDB and Table Variables are created In-Memory. Fact is that both are created in TempDB, below Demos prove this reality.
4. TRANSACTIONS
Temporary Tables honor the explicit transactions defined by the user. Table variables doesn’t participate in the explicit transactions defined by the user.
5. USER DEFINED FUNCTION
Temporary Tables are not allowed in User Defined Functions. Table Variables can be used in User Defined Functions.
6. INDEXES
Temporary table supports adding Indexes explicitly after Temporary Table creation and it can also have the implicit Indexes which are the result of Primary and Unique Key constraint. Table Variables doesn’t allow the explicit addition of Indexes after it’s declaration, the only means is the implicit indexes which are created as a result of the Primary Key or Unique Key constraint defined during Table Variable declaration.
7. SCOPE
There are two types of Temporary Tables, one Local Temporary Tables whose name starts with single # sign and other one is Global Temporary Tables whose name starts with two # signs.Scope of the Local Temporary Table is the session in which it is created and they are dropped automatically once the session ends and we can also drop them explicitly. If a Temporary Table is created within a batch, then it can be accessed within the next batch of the same session. Whereas if a Local Temporary Table is created within a stored procedure then it can be accessed in it’s child stored procedures, but it can’t be accessed outside the stored procedure.Scope of Global Temporary Table is not only to the session which created, but they will visible to all other sessions. They can be dropped explicitly or they will get dropped automatically when the session which created it terminates and none of the other sessions are using it. Scope of the Table variable is the Batch or Stored Procedure in which it is declared. And they can’t be dropped explicitly, they are dropped automatically when batch execution completes or the Stored Procedure execution completes.

The above listed differences are discussed in-detail with extensive list of examples in the below articles:

ALSO READ

How to get Day, Month and Year Part from DateTime in Sql Server

Many a times we may need to get Day, Month and Year Part from DateTime in Sql Server. In this article we will see how we can get these parts of the DateTime in Sql Server.

You may like to read the other popular articles on Date and Time:

1. DAY part of DateTime in Sql Server

Following are the different ways of getting DAY part of the DateTime in Sql Server

[ALSO READ] How to get Day or Weekday name from date in Sql Server

Approach 1: Using DAY Function

We can use DAY() function to get the DAY part of the DateTime in Sql Server.

SELECT GETDATE() 'Today', DAY(GETDATE()) 'Day Part'

RESULT:
DayPart1

Approach 2: Using DATEPART Function

We can use DATEPART() function to get DAY part of the DateTime in Sql Server, here we need specify datepart parameter of the DATEPART function as day or dd or d all will return the same result.

SELECT GETDATE() 'Today', DATEPART(day,GETDATE()) 'Day Part'
SELECT GetDate() 'Today', DATEPART(dd,GETDATE())  'Day Part'
SELECT GetDate() 'Today', DATEPART(d,GETDATE())	  'Day Part'

RESULT:
DayPart2

Approach 3: Day returned should always be of TWO digits.

If we see the previous two approaches as Today is 3rd day of February, it is always returning day as 3 i.e one digit instead of 03. Below examples shows how to get two digits day part of a DateTime.

SELECT GETDATE() 'Today', 
  CONVERT(varchar(2), getdate(), 103) 'Day Part'
SELECT GETDATE() 'Today', 
  RIGHT('0' + CAST(DAY(GETDATE()) AS varchar(2)), 2) 'Day Part'

RESULT:
DayPart3

2. MONTH part of DateTime in Sql Server

Following are the different ways of getting MONTH part of the DateTime in Sql Server

[ALSO READ] How to get month name from date in Sql Server

Approach 1: Using MONTH Function

We can use MONTH() function to get the MONTH part of the DateTime in Sql Server.

SELECT GETDATE() 'Today', MONTH(GETDATE()) 'MONTH Part'

RESULT:
MonthPart1

Approach 2: Using DATEPART Function

We can use DATEPART() function to get MONTH part of the DateTime in Sql Server, here we need specify datepart parameter of the DATEPART function as month or mm or all will return the same result.

SELECT GETDATE() 'Today',DATEPART(month,GETDATE()) 'Month Part'
SELECT GetDate() 'Today', DATEPART(mm,GETDATE())  'Month Part'
SELECT GetDate() 'Today', DATEPART(m,GETDATE())	  'Month Part'

RESULT:
MonthPart2

Approach 3: Month returned should always be of TWO digits.

If we see the previous two approaches as Today’s month is February, it is always returning month as 2 i.e one digit instead of 02. Below examples shows how to get two digits month part of a DateTime.

SELECT GETDATE() 'Today', 
 CONVERT(varchar(2), getdate(), 101) 'Month Part'
SELECT GETDATE() 'Today', 
 RIGHT('0'+CAST(MONTH(GETDATE()) AS varchar(2)),2) 'Month Part'

RESULT:
MonthPart3

3. YEAR part of DateTime in Sql Server

Following are the different ways of getting YEAR part of the DateTime in Sql Server

Approach 1: Using YEAR Function

We can use YEAR() function to get the YEAR part of the DateTime in Sql Server.

SELECT GETDATE() 'Today', YEAR(GETDATE()) 'YEAR Part'

RESULT:
YearPart1

Approach 2: Using DATEPART Function

We can use DATEPART() function to get YEAR part of the DateTime in Sql Server, here we need specify datepart parameter of the DATEPART function as year or yyyy or yy all will return the same result.

SELECT GETDATE() 'Today', DATEPART(year,GETDATE()) 'Year Part'
SELECT GetDate() 'Today', DATEPART(yyyy,GETDATE()) 'Year Part'
SELECT GetDate() 'Today', DATEPART(yy,GETDATE())   'Year Part'

RESULT:
YearPart2

How to get Date Part only from DateTime in Sql Server

Many times we come across a scenario where we need to get Date Part only from DateTime in Sql Server. There are multiple ways of doing this, here I am listing out few of them:

1) Below approach works in Sql Server 2008 and above:

SELECT CONVERT (DATE, GETDATE()) 'Date Part Only'

RESULT:
Date Part Only
--------------
2013-07-14

2) Below approaches works in all the versions of Sql server

i) Get Date Part only from DateTime using CONVERT function
Example 1:

SELECT CONVERT(VARCHAR(10), GETDATE(), 112) 'Date Part Only'

RESULT:
Date Part Only
--------------
20130714

Example 2:

SELECT CONVERT(VARCHAR(10), GETDATE(), 111) 'Date Part Only'

RESULT:
Date Part Only
--------------
2013/07/14

The results of the above query is of type VARCHAR, if we want the result to be of type DATETIME we can write a query like below:

Example 1:

SELECT CONVERT(DATETIME,
			CONVERT(VARCHAR(10), GETDATE(), 112)) 'Date Part Only'

RESULT:
Date Part Only
-----------------------
2013-07-14 00:00:00.000

Example 2:

SELECT CONVERT(DATETIME,
			CONVERT(VARCHAR(10), GETDATE(), 111)) 'Date Part Only'

RESULT:
Date Part Only
-----------------------
2013-07-14 00:00:00.000

ii) Get Date Part only from DateTime using DateTime functions

From performance perspective this is the better approach instead of first converting DATETIME to VARCHAR and then VARCHAR to DATETIME.

Example 1:

SELECT DATEADD(dd, 0, 
        DATEDIFF(dd, 0, GETDATE())) 'Date Part Only'

RESULT:
Date Part Only
-----------------------
2013-07-14 00:00:00.000

Example 2:

DECLARE  @DatePartOnly DATETIME
SEt @DatePartOnly = DATEDIFF(DD, 0, GETDATE())
SELECT @DatePartOnly 'Date Part Only'

RESULT:
Date Part Only
-----------------------
2013-07-14 00:00:00.000

iii) Get Date Part only from DateTime using FLOOR and CAST functions

As we know Sql Server internally stores DATETIME as two 4-byte integers. First 4-byte stores the elapsed number days since SQL Server’s DATETIME type’s start date 19000101.The Second 4-bytes Store the Time of Day i.e. clock-ticks since midnight. Each clock-tick is equivalent to 3.33 milliseconds.

So with above said internal storgae of the DATETIME, we can first convert the DATETIME to DECIMAL, then from decimal part ignore the fractional position and get only the integer part. Finally convert the integer to DATETIME as shown below:

SELECT CAST( -- Convert the integer to DATE
         FLOOR(-- Get largest Integer less than or equal to the decimal value
                CAST(GETDATE() AS DECIMAL(12, 5)) -- Convert DATETIME to DECIMAL
              ) 
         AS DATETIME) 'Date Part Only'

RESULT:
Date Part Only
-----------------------
2013-07-14 00:00:00.000

iv) Get Date Part only from DateTime using DATEPART and CONVERT functions

DECLARE @GETDATE AS DATETIME = GETDATE()
SELECT CONVERT(VARCHAR(4),DATEPART(YEAR, @GETDATE)) 
       + '/'+ CONVERT(VARCHAR(2),DATEPART(MONTH, @GETDATE)) 
       + '/' + CONVERT(VARCHAR(2),DATEPART(DAY, @GETDATE)) 
         'Date Part Only'

RESULT:
Date Part Only
--------------
2013/7/14

You may like to read the other popular articles on Date and Time: