Monday, March 28, 2011

Oracle vs SQL Server SQLs for date formats

DESCRIPTIONORACLE / SQL-SERVER SQL

Current system date

SELECT SYSDATE FROM DUAL

SELECT GETDATE()

Current date as char

SELECT TO_CHAR(SYSDATE, 'MMDDYYYY') FROM DUAL
**Change format mask as you want

SELECT CONVERT(VARCHAR, GETDATE(), 112)
**Use format mask as per below table
1 or 101 - US Foramt - Displays as MM/DD/YY or MM/DD/YYYY
2 or 102 - ANSI Foramt - Displays as YY.MM.DD or YYYY.MM.DD
3 or 103 - UK Format - Displays as DD/MM/YY or DD/MM/YYYY
10 or 110 - US Format - Displays as MM-DD-YY or MM-DD-YYYY
11 or 111 - Japan Format - Displays as YY/MM/DD or YYYY/MM/DD
12 or 112 - ISO Format - Displays as YYMMDD or YYYYMMDD

Current time as char

SELECT TO_CHAR(SYSDATE, 'HH24:MI:SS') FROM DUAL
**Change format mask as you want

SELECT CONVERT(VARCHAR, GETDATE(), 108)
**Use format mask as per below table
8 or 108 - Displays as hh:mi:ss(24h)
14 or 114 - Displays as hh:mi:ss:mmm(24h)

Current date-time as char

SELECT TO_CHAR(SYSDATE, 'MMDDYYYY HH24:MI:SS') FROM DUAL
**Change format mask as you want

SELECT CONVERT(VARCHAR, GETDATE(), 113)
**Use format mask as per below table
13 or 113 - Displays as dd mon yyyy hh:mi:ss:mmm(24h)
20 or 120 - Displays as yyyy-mm-dd hh:mi:ss(24h)
21 or 121 - Displays as yyyy-mm-dd hh:mi:ss.mmm(24h)

Convert char to date

SELECT TO_DATE('03232011','MMDDYYYY') FROM DUAL

SELECT CONVERT(DATE, '20110323', 112) --Use mask as per format

Last day of current month

SELECT LAST_DAY(SYSDATE) FROM DUAL

SELECT DATEADD(S,-1,DATEADD(M, DATEDIFF(M,0,GETDATE())+1,0))

Last day of next month

SELECT LAST_DAY(ADD_MONTHS(SYSDATE, 1)) FROM DUAL

SELECT DATEADD(S,-1,DATEADD(M, DATEDIFF(M,0,GETDATE())+2,0))

Last day of previous month

SELECT LAST_DAY(ADD_MONTHS(SYSDATE, -1)) FROM DUAL

SELECT DATEADD(S,-1,DATEADD(M, DATEDIFF(M,0,GETDATE()),0))

Add a day

SELECT SYSDATE + 1 FROM DUAL

SELECT DATEADD(D, 1, GETDATE())

Subtract a day

SELECT SYSDATE - 1 FROM DUAL

SELECT DATEADD(D, -1, GETDATE())

Add a year

SELECT ADD_MONTHS(SYSDATE, 12) FROM DUAL

SELECT DATEADD(YY, 1, GETDATE())

Subtract a year

SELECT ADD_MONTHS(SYSDATE, -12) FROM DUAL

SELECT DATEADD(YY, -1, GETDATE())

No comments: