Commonly used function in SQL Server

Commonly used function in SQL Server (part1)

Overview


DateTime Function in SQL Server

Dưới đây là các hàm thường được dùng nhiều nhất để xử lý các dữ liệu kiểu DateTime trong SQL Server.
  • GETDATE()
  • DATEADD()
  • DATEPART()
  • DATEDIFF()
  • DATENAME()
  • DAY()
  • MONTH()
  • YEAR()

GETDATE()

GETDATE() là hàm rất thường được dùng nó đưa ra thời gian lúc runtime của hệ thống. Nó không cần truyền bất cứ tham số nào. 

Example :


Declare @Date datetime 
set @Date = (SELECT GETDATE());
Print @Date 

OutPut:


Aug 15 2009  9:04PM 


DATEADD()

DATEADD() được sử dụng để thêm hoặc bớt thời gian trong dữ liệu datetime. Nó trả về dữ liệu datetime mới dựa vào khoảng thời gian được thêm hoặc bớt trong tham số truyền vào.

General Syntax


DATEADD(datepart, number, date)


datepart is the parameter that specifies on which part of the date to return a new value. Number parameter is used to increment datepart.

Example :


Declare @Date datetime 
set @Date = (SELECT GETDATE());
print  @Date -- Print Current Date
-- Adding 5 days with Current Date
SELECT DATEADD(day, 5,@Date ) AS NewTime

Output :


Aug 15 2009  9:19PM
NewTime
-----------------------
2009-08-20 21:19:15.170


DATEPART()

DATEPART() sử dụng khi chỉ muốn lấy một phần của dữ liệu datetime như (ngày, tháng, năm, giờ, phút, ... ). Chỉ sử dụng được DATEPART() trong câu lệnh SELECT
Syntax


DATEPART(datepart, date)

Example :


-- Get Only Year
SELECT DATEPART(year, GETDATE()) AS 'Year'
-- Get Only Month
SELECT DATEPART(month, GETDATE()) AS 'Month'
-- Get Only hour
SELECT DATEPART(hour, GETDATE()) AS 'Hour

Output :


Year
-----------
2009
Month
-----------
8
Hour
-----------
21


DATEDIFF()

DATEDIFF() cũng là hàm được sử dụng rất nhiều để tìm ra sự khác nhau giữa 2 dữ liệu  DateTime.

Syntax


DATEDIFF(datepart, startdate, enddate)

Example :


-- Declare Two DateTime Variable
Declare @Date1 datetime 
Declare @Date2 datetime 
-- Set @Date1 with Current Date
set @Date1 = (SELECT GETDATE());
-- Set @Date2 with 5 days more than @Date1
set @Date2 = (SELECT DATEADD(day, 5,@Date1 ))
-- Get The Date Difference
SELECT DATEDIFF(day, @Date1, @Date2) AS DifferenceOfDay

Output :


DifferenceOfDay
---------------
5 


DATENAME()

DATENAME() sử dụng khi muốn lấy dữ liệu tên của dữ liệu datetime như thứ mấy,  tháng mấy,...

Example


-- Get Today 
SELECT DATENAME(dw, getdate()) AS 'Today Is'
-- Get Mont name
SELECT DATENAME(month, getdate()) AS 'Month'


Output :
Today Is
------------------------------
Saturday
Month
------------------------------
August


DAY()

DAY() sử dụng lấy ngày từ các dữ liệu datetime.

Example:
SELECT DAY(getdate()) AS 'DAY'
Output :
DAY
-----------
15

MONTH()

SELECT MONTH(getdate()) AS 'Month'
Output :
Month
-----------
8

YEAR()

SELECT YEAR(getdate()) AS 'Year'
Output :
Year
-----------
2009

Refference:



Nhận xét

Bài đăng phổ biến từ blog này

Material Tree

.Net secure coding guidelines

Tìm hiểm Checkbox Angular Material