Execute the following Microsoft SQL Server T-SQL datetime and date formatting scripts in Management Studio Query Editor to demonstrate the multitude of temporal data formats available in SQL Server.

First we start with the conversion options available for sql datetime formats with century (YYYY or CCYY format). Subtracting 100 from the Style (format) number will transform dates without century (YY). For example Style 103 is with century, Style 3 is without century. The default Style values – Style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121 – always return the century (yyyy) format.

  1. – Microsoft SQL Server T-SQL date and datetime formats
  2. Date time formats – mssql datetime
  3. – MSSQL getdate returns current system date and time in standard internal format
  4. SELECT convert(varchar, getdate(), 100) – mon dd yyyy hh:mmAM (or PM)
  5. – Oct 2 2008 11:01AM
  6. SELECT convert(varchar, getdate(), 101) – mm/dd/yyyy - 10/02/2008
  7. SELECT convert(varchar, getdate(), 102) – yyyy.mm.dd – 2008.10.02
  8. SELECT convert(varchar, getdate(), 103) – dd/mm/yyyy
  9. SELECT convert(varchar, getdate(), 104) – dd.mm.yyyy
  10. SELECT convert(varchar, getdate(), 105) – dd-mm-yyyy
  11. SELECT convert(varchar, getdate(), 106) – dd mon yyyy
  12. SELECT convert(varchar, getdate(), 107) – mon dd, yyyy
  13. SELECT convert(varchar, getdate(), 108) – hh:mm:ss
  14. SELECT convert(varchar, getdate(), 109) – mon dd yyyy hh:mm:ss:mmmAM (or PM)
  15. – Oct 2 2008 11:02:44:013AM
  16. SELECT convert(varchar, getdate(), 110) – mm-dd-yyyy
  17. SELECT convert(varchar, getdate(), 111) – yyyy/mm/dd
  18. SELECT convert(varchar, getdate(), 112) – yyyymmdd
  19. SELECT convert(varchar, getdate(), 113) – dd mon yyyy hh:mm:ss:mmm
  20. – 02 Oct 2008 11:02:07:577
  21. SELECT convert(varchar, getdate(), 114) – hh:mm:ss:mmm(24h)
  22. SELECT convert(varchar, getdate(), 120) – yyyy-mm-dd hh:mm:ss(24h)
  23. SELECT convert(varchar, getdate(), 121) – yyyy-mm-dd hh:mm:ss.mmm
  24. SELECT convert(varchar, getdate(), 126) – yyyy-mm-ddThh:mm:ss.mmm
  25. – 2008-10-02T10:52:47.513
  26. – SQL create different date styles with t-sql string functions
  27. SELECT replace(convert(varchar, getdate(), 111), ‘/’, ‘ ‘) – yyyy mm dd
  28. SELECT convert(varchar(7), getdate(), 126) – yyyy-mm
  29. SELECT right(convert(varchar, getdate(), 106), 8) – mon yyyy
  30. ————
  31. – SQL Server date formatting functionconvert datetime to string
  32. ————
  33. – SQL datetime functions
  34. – SQL Server date formats
  35. – T-SQL convert dates
  36. – Formatting dates sql server
  37. CREATE FUNCTION dbo.fnFormatDate (@Datetime DATETIME, @FormatMask VARCHAR(32))
  38. RETURNS VARCHAR(32)
  39. AS
  40. BEGIN
  41. DECLARE @StringDate VARCHAR(32)
  42. SET @StringDate = @FormatMask
  43. IF (CHARINDEX (‘YYYY’,@StringDate) > 0)
  44. SET @StringDate = REPLACE(@StringDate, ‘YYYY’,
  45. DATENAME(YY, @Datetime))
  46. IF (CHARINDEX (‘YY’,@StringDate) > 0)
  47. SET @StringDate = REPLACE(@StringDate, ‘YY’,
  48. RIGHT(DATENAME(YY, @Datetime),2))
  49. IF (CHARINDEX (‘Month’,@StringDate) > 0)
  50. SET @StringDate = REPLACE(@StringDate, ‘Month’,
  51. DATENAME(MM, @Datetime))
  52. IF (CHARINDEX (‘MON’,@StringDate COLLATE SQL_Latin1_General_CP1_CS_AS)>0)
  53. SET @StringDate = REPLACE(@StringDate, ‘MON’,
  54. LEFT(UPPER(DATENAME(MM, @Datetime)),3))
  55. IF (CHARINDEX (‘Mon’,@StringDate) > 0)
  56. SET @StringDate = REPLACE(@StringDate, ‘Mon’,
  57. LEFT(DATENAME(MM, @Datetime),3))
  58. IF (CHARINDEX (‘MM’,@StringDate) > 0)
  59. SET @StringDate = REPLACE(@StringDate, ‘MM’,
  60. RIGHT(‘0’+CONVERT(VARCHAR,DATEPART(MM, @Datetime)),2))
  61. IF (CHARINDEX (‘M’,@StringDate) > 0)
  62. SET @StringDate = REPLACE(@StringDate, ‘M’,
  63. CONVERT(VARCHAR,DATEPART(MM, @Datetime)))
  64. IF (CHARINDEX (‘DD’,@StringDate) > 0)
  65. SET @StringDate = REPLACE(@StringDate, ‘DD’,
  66. RIGHT(‘0’+DATENAME(DD, @Datetime),2))
  67. IF (CHARINDEX (‘D’,@StringDate) > 0)
  68. SET @StringDate = REPLACE(@StringDate, ‘D’,
  69. DATENAME(DD, @Datetime))
  70. RETURN @StringDate
  71. END
  72. GO
  73. – Microsoft SQL Server date format function test
  74. – MSSQL formatting dates
  75. SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YYYY’) – 01/03/2012
  76. SELECT dbo.fnFormatDate (getdate(), ‘DD/MM/YYYY’) – 03/01/2012
  77. SELECT dbo.fnFormatDate (getdate(), ‘M/DD/YYYY’) – 1/03/2012
  78. SELECT dbo.fnFormatDate (getdate(), ‘M/D/YYYY’) – 1/3/2012
  79. SELECT dbo.fnFormatDate (getdate(), ‘M/D/YY’) – 1/3/12
  80. SELECT dbo.fnFormatDate (getdate(), ‘MM/DD/YY’) – 01/03/12
  81. SELECT dbo.fnFormatDate (getdate(), ‘MON DD, YYYY’) – JAN 03, 2012
  82. SELECT dbo.fnFormatDate (getdate(), ‘Mon DD, YYYY’) – Jan 03, 2012
  83. SELECT dbo.fnFormatDate (getdate(), ‘Month DD, YYYY’) – January 03, 2012
  84. SELECT dbo.fnFormatDate (getdate(), ‘YYYY/MM/DD’) – 2012/01/03
  85. SELECT dbo.fnFormatDate (getdate(), ‘YYYYMMDD’) – 20120103
  86. SELECT dbo.fnFormatDate (getdate(), ‘YYYY-MM-DD’) – 2012-01-03
  87. CURRENT_TIMESTAMP returns current system date and time in standard internal format
  88. SELECT dbo.fnFormatDate (CURRENT_TIMESTAMP,‘YY.MM.DD’) – 12.01.03
  89. GO
  90. ————
  91. /***** SELECTED SQL DATE/DATETIME FORMATS WITH NAMES *****/
  92. – SQL format datetime
  93. Default format: Oct 23 2006 10:40AM
  94. SELECT [Default]=CONVERT(varchar,GETDATE(),100)
  95. – US-Style format: 10/23/2006
  96. SELECT [US-Style]=CONVERT(char,GETDATE(),101)
  97. – ANSI format: 2006.10.23
  98. SELECT [ANSI]=CONVERT(char,CURRENT_TIMESTAMP,102)
  99. – UK-Style format: 23/10/2006
  100. SELECT [UK-Style]=CONVERT(char,GETDATE(),103)
  101. – German format: 23.10.2006
  102. SELECT [German]=CONVERT(varchar,GETDATE(),104)
  103. – ISO format: 20061023
  104. SELECT ISO=CONVERT(varchar,GETDATE(),112)
  105. – ISO8601 format: 2008-10-23T19:20:16.003
  106. SELECT [ISO8601]=CONVERT(varchar,GETDATE(),126)
  107. ————
  108. – SQL Server datetime formats
  109. – Century date format MM/DD/YYYY usage in a query
  110. – Format dates SQL Server 2005
  111. SELECT TOP (1)
  112. SalesOrderID,
  113. OrderDate = CONVERT(char(10), OrderDate, 101),
  114. OrderDateTime = OrderDate
  115. FROM AdventureWorks.Sales.SalesOrderHeader
  116. /* Result
  117. SalesOrderID OrderDate OrderDateTime
  118. 43697 07/01/2001 2001-07-01 00:00:00.000
  119. */
  120. – SQL update datetime column
  121. – SQL datetime DATEADD
  122. UPDATE Production.Product
  123. SET ModifiedDate=DATEADD(dd,1, ModifiedDate)
  124. WHERE ProductID = 1001
  125. – MM/DD/YY date format
  126. – Datetime format sql
  127. SELECT TOP (1)
  128. SalesOrderID,
  129. OrderDate = CONVERT(varchar(8), OrderDate, 1),
  130. OrderDateTime = OrderDate
  131. FROM AdventureWorks.Sales.SalesOrderHeader
  132. ORDER BY SalesOrderID desc
  133. /* Result
  134. SalesOrderID OrderDate OrderDateTime
  135. 75123 07/31/04 2004-07-31 00:00:00.000
  136. */
  137. – Combining different style formats for date & time
  138. – Datetime formats
  139. – Datetime formats sql
  140. DECLARE @Date DATETIME
  141. SET @Date = ‘2015-12-22 03:51 PM’
  142. SELECT CONVERT(CHAR(10),@Date,110) + SUBSTRING(CONVERT(varchar,@Date,0),12,8)
  143. – Result: 12-22-2015 3:51PM
  144. – Microsoft SQL Server cast datetime to string
  145. SELECT stringDateTime=CAST (getdate() as varchar)
  146. – Result: Dec 29 2012 3:47AM
  147. ————
  148. – SQL Server date and time functions overview
  149. ————
  150. – SQL Server CURRENT_TIMESTAMP function
  151. – SQL Server datetime functions
  152. local NYC – EST – Eastern Standard Time zone
  153. – SQL DATEADD function – SQL DATEDIFF function
  154. SELECT CURRENT_TIMESTAMP – 2012-01-05 07:02:10.577
  155. – SQL Server DATEADD function
  156. SELECT DATEADD(month,2,‘2012-12-09′) – 2013-02-09 00:00:00.000
  157. – SQL Server DATEDIFF function
  158. SELECT DATEDIFF(day,‘2012-12-09′,‘2013-02-09′) – 62
  159. – SQL Server DATENAME function
  160. SELECT DATENAME(month, ‘2012-12-09′) – December
  161. SELECT DATENAME(weekday, ‘2012-12-09′) – Sunday
  162. – SQL Server DATEPART function
  163. SELECT DATEPART(month, ‘2012-12-09′) – 12
  164. – SQL Server DAY function
  165. SELECT DAY(‘2012-12-09′) – 9
  166. – SQL Server GETDATE function
  167. local NYC – EST – Eastern Standard Time zone
  168. SELECT GETDATE() – 2012-01-05 07:02:10.577
  169. – SQL Server GETUTCDATE function
  170. – London – Greenwich Mean Time
  171. SELECT GETUTCDATE() – 2012-01-05 12:02:10.577
  172. – SQL Server MONTH function
  173. SELECT MONTH(‘2012-12-09′) – 12
  174. – SQL Server YEAR function
  175. SELECT YEAR(‘2012-12-09′) – 2012
  176. ————
  177. – T-SQL Date and time function application
  178. CURRENT_TIMESTAMP and getdate() are the same in T-SQL
  179. ————
  180. – SQL first day of the month
  181. – SQL first date of the month
  182. – SQL first day of current month – 2012-01-01 00:00:00.000
  183. SELECT DATEADD(dd,0,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP),0))
  184. – SQL last day of the month
  185. – SQL last date of the month
  186. – SQL last day of current month – 2012-01-31 00:00:00.000
  187. SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP)+1,0))
  188. – SQL first day of last month
  189. – SQL first day of previous month – 2011-12-01 00:00:00.000
  190. SELECT DATEADD(mm,-1,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP),0))
  191. – SQL last day of last month
  192. – SQL last day of previous month – 2011-12-31 00:00:00.000
  193. SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,DATEADD(MM,-1,GETDATE()))+1,0))
  194. – SQL first day of next month – 2012-02-01 00:00:00.000
  195. SELECT DATEADD(mm,1,DATEADD(mm, DATEDIFF(mm,0,CURRENT_TIMESTAMP),0))
  196. – SQL last day of next month – 2012-02-28 00:00:00.000
  197. SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,DATEADD(MM,1,GETDATE()))+1,0))
  198. GO
  199. – SQL first day of a month – 2012-10-01 00:00:00.000
  200. DECLARE @Date datetime; SET @Date = ‘2012-10-23′
  201. SELECT DATEADD(dd,0,DATEADD(mm, DATEDIFF(mm,0,@Date),0))
  202. GO
  203. – SQL last day of a month – 2012-03-31 00:00:00.000
  204. DECLARE @Date datetime; SET @Date = ‘2012-03-15′
  205. SELECT DATEADD(dd,-1,DATEADD(mm, DATEDIFF(mm,0,@Date)+1,0))
  206. GO
  207. – SQL first day of year
  208. – SQL first day of the year – 2012-01-01 00:00:00.000
  209. SELECT DATEADD(yy, DATEDIFF(yy,0,CURRENT_TIMESTAMP), 0)
  210. – SQL last day of year
  211. – SQL last day of the year – 2012-12-31 00:00:00.000
  212. SELECT DATEADD(yy,1, DATEADD(dd, -1, DATEADD(yy,
  213. DATEDIFF(yy,0,CURRENT_TIMESTAMP), 0)))
  214. – SQL last day of last year
  215. – SQL last day of previous year – 2011-12-31 00:00:00.000
  216. SELECT DATEADD(dd,-1,DATEADD(yy,DATEDIFF(yy,0,CURRENT_TIMESTAMP), 0))
  217. GO
  218. – SQL calculate age in years, months, days
  219. – SQL table-valued function
  220. – SQL user-defined function – UDF
  221. – SQL Server age calculation – date difference
  222. – Format dates SQL Server 2008
  223. USE AdventureWorks2008;
  224. GO
  225. CREATE FUNCTION fnAge (@BirthDate DATETIME)
  226. RETURNS @Age TABLE(Years INT,
  227. Months INT,
  228. Days INT)
  229. AS
  230. BEGIN
  231. DECLARE @EndDate DATETIME, @Anniversary DATETIME
  232. SET @EndDate = Getdate()
  233. SET @Anniversary = Dateadd(yy,Datediff(yy,@BirthDate,@EndDate),@BirthDate)
  234. INSERT @Age
  235. SELECT Datediff(yy,@BirthDate,@EndDate) - (CASE
  236. WHEN @Anniversary > @EndDate THEN 1
  237. ELSE 0
  238. END), 0, 0
  239. UPDATE @Age SET Months = Month(@EndDate - @Anniversary) - 1
  240. UPDATE @Age SET Days = Day(@EndDate - @Anniversary) - 1
  241. RETURN
  242. END
  243. GO
  244. – Test table-valued UDF
  245. SELECT * FROM fnAge(‘1956-10-23′)
  246. SELECT * FROM dbo.fnAge(‘1956-10-23′)
  247. /* Results
  248. Years Months Days
  249. 52 4 1
  250. */
  251. ———-
  252. – SQL date range between
  253. ———-
  254. – SQL between dates
  255. USE AdventureWorks;
  256. – SQL between
  257. SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader
  258. WHERE OrderDate BETWEEN ‘20040301’ AND ‘20040315’
  259. – Result: 108
  260. BETWEEN operator is equivalent to >=…AND….<=
  261. SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader
  262. WHERE OrderDate
  263. BETWEEN ‘2004-03-01 00:00:00.000′ AND ‘2004-03-15 00:00:00.000′
  264. /*
  265. Orders with OrderDates
  266. ‘2004-03-15 00:00:01.000′ – 1 second after midnight (12:00AM)
  267. ‘2004-03-15 00:01:00.000′ – 1 minute after midnight
  268. ‘2004-03-15 01:00:00.000′ – 1 hour after midnight
  269. are not included in the two queries above.
  270. */
  271. To include the entire day of 2004-03-15 use the following two solutions
  272. SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader
  273. WHERE OrderDate >= ‘20040301’ AND OrderDate < ‘20040316’
  274. – SQL between with DATE type (SQL Server 2008)
  275. SELECT POs=COUNT(*) FROM Purchasing.PurchaseOrderHeader
  276. WHERE CONVERT(DATE, OrderDate) BETWEEN ‘20040301’ AND ‘20040315’
  277. ———-
  278. – Non-standard format conversion: 2011 December 14
  279. – SQL datetime to string
  280. SELECT [YYYY Month DD] =
  281. CAST(YEAR(GETDATE()) AS VARCHAR(4))+ ‘ ‘+
  282. DATENAME(MM, GETDATE()) + ‘ ‘ +
  283. CAST(DAY(GETDATE()) AS VARCHAR(2))
  284. – Converting datetime to YYYYMMDDHHMMSS format: 20121214172638
  285. SELECT replace(convert(varchar, getdate(),111),‘/’,”) +
  286. replace(convert(varchar, getdate(),108),‘:’,”)
  287. – Datetime custom format conversion to YYYY_MM_DD
  288. select CurrentDate=rtrim(year(getdate())) + ‘_’ +
  289. right(‘0’ + rtrim(month(getdate())),2) + ‘_’ +
  290. right(‘0’ + rtrim(day(getdate())),2)
  291. – Converting seconds to HH:MM:SS format
  292. declare @Seconds int
  293. set @Seconds = 10000
  294. select TimeSpan=right(‘0’ +rtrim(@Seconds / 3600),2) + ‘:’ +
  295. right(‘0’ + rtrim((@Seconds % 3600) / 60),2) + ‘:’ +
  296. right(‘0’ + rtrim(@Seconds % 60),2)
  297. – Result: 02:46:40
  298. – Test result
  299. select 2*3600 + 46*60 + 40
  300. – Result: 10000
  301. Set the time portion of a datetime value to 00:00:00.000
  302. – SQL strip time from date
  303. – SQL strip time from datetime
  304. SELECT CURRENT_TIMESTAMP ,DATEADD(dd, DATEDIFF(dd, 0, CURRENT_TIMESTAMP), 0)
  305. – Results: 2014-01-23 05:35:52.793 2014-01-23 00:00:00.000
  306. /*******
  307. VALID DATE RANGES FOR DATE/DATETIME DATA TYPES
  308. SMALLDATETIME date range:
  309. January 1, 1900 through June 6, 2079
  310. DATETIME date range:
  311. January 1, 1753 through December 31, 9999
  312. DATETIME2 date range (SQL Server 2008):
  313. January 1,1 AD through December 31, 9999 AD
  314. DATE date range (SQL Server 2008):
  315. January 1, 1 AD through December 31, 9999 AD
  316. *******/
  317. – Selecting with CONVERT into different styles
  318. – Note: Only Japan & ISO styles can be used in ORDER BY
  319. SELECT TOP(1)
  320. Italy = CONVERT(varchar, OrderDate, 105)
  321. , USA = CONVERT(varchar, OrderDate, 110)
  322. , Japan = CONVERT(varchar, OrderDate, 111)
  323. , ISO = CONVERT(varchar, OrderDate, 112)
  324. FROM AdventureWorks.Purchasing.PurchaseOrderHeader
  325. ORDER BY PurchaseOrderID DESC
  326. /* Results
  327. Italy USA Japan ISO
  328. 25-07-2004 07-25-2004 2004/07/25 20040725
  329. */
  330. – SQL Server convert date to integer
  331. DECLARE @Datetime datetime
  332. SET @Datetime = ‘2012-10-23 10:21:05.345′
  333. SELECT DateAsInteger = CAST (CONVERT(varchar,@Datetime,112) as INT)
  334. – Result: 20121023
  335. – SQL Server convert integer to datetime
  336. DECLARE @intDate int
  337. SET @intDate = 20120315
  338. SELECT IntegerToDatetime = CAST(CAST(@intDate as varchar) as datetime)
  339. – Result: 2012-03-15 00:00:00.000
  340. ————
  341. – SQL Server CONVERT script applying table INSERT/UPDATE
  342. ————
  343. – SQL Server convert date
  344. – Datetime column is converted into date only string column
  345. USE tempdb;
  346. GO
  347. CREATE TABLE sqlConvertDateTime (
  348. DatetimeCol datetime,
  349. DateCol char(8));
  350. INSERT sqlConvertDateTime (DatetimeCol) SELECT GETDATE()
  351. UPDATE sqlConvertDateTime
  352. SET DateCol = CONVERT(char(10), DatetimeCol, 112)
  353. SELECT * FROM sqlConvertDateTime
  354. – SQL Server convert datetime
  355. – The string date column is converted into datetime column
  356. UPDATE sqlConvertDateTime
  357. SET DatetimeCol = CONVERT(Datetime, DateCol, 112)
  358. SELECT * FROM sqlConvertDateTime
  359. – Adding a day to the converted datetime column with DATEADD
  360. UPDATE sqlConvertDateTime
  361. SET DatetimeCol = DATEADD(day, 1, CONVERT(Datetime, DateCol, 112))
  362. SELECT * FROM sqlConvertDateTime
  363. – Equivalent formulation
  364. – SQL Server cast datetime
  365. UPDATE sqlConvertDateTime
  366. SET DatetimeCol = DATEADD(dd, 1, CAST(DateCol AS datetime))
  367. SELECT * FROM sqlConvertDateTime
  368. GO
  369. DROP TABLE sqlConvertDateTime
  370. GO
  371. /* First results
  372. DatetimeCol DateCol
  373. 2014-12-25 16:04:15.373 20141225 */
  374. /* Second results:
  375. DatetimeCol DateCol
  376. 2014-12-25 00:00:00.000 20141225 */
  377. /* Third results:
  378. DatetimeCol DateCol
  379. 2014-12-26 00:00:00.000 20141225 */
  380. ————
  381. – SQL month sequence – SQL date sequence generation with table variable
  382. – SQL Server cast string to datetime – SQL Server cast datetime to string
  383. – SQL Server insert default values method
  384. DECLARE @Sequence table (Sequence int identity(1,1))
  385. DECLARE @i int; SET @i = 0
  386. DECLARE @StartDate datetime;
  387. SET @StartDate = CAST(CONVERT(varchar, year(getdate()))+
  388. RIGHT(‘0’+convert(varchar,month(getdate())),2) + ’01’ AS DATETIME)
  389. WHILE ( @i < 120)
  390. BEGIN
  391. INSERT @Sequence DEFAULT VALUES
  392. SET @i = @i + 1
  393. END
  394. SELECT MonthSequence = CAST(DATEADD(month, Sequence,@StartDate) AS varchar)
  395. FROM @Sequence
  396. GO
  397. /* Partial results:
  398. MonthSequence
  399. Jan 1 2012 12:00AM
  400. Feb 1 2012 12:00AM
  401. Mar 1 2012 12:00AM
  402. Apr 1 2012 12:00AM
  403. */
  404. ————
  405. ————
  406. – SQL Server Server datetime internal storage
  407. – SQL Server datetime formats
  408. ————
  409. – SQL Server datetime to hex
  410. SELECT Now=CURRENT_TIMESTAMP, HexNow=CAST(CURRENT_TIMESTAMP AS BINARY(8))
  411. /* Results
  412. Now HexNow
  413. 2009-01-02 17:35:59.297 0x00009B850122092D
  414. */
  415. – SQL Server date part – left 4 bytes – Days since 1900-01-01
  416. SELECT Now=DATEADD(DAY, CONVERT(INT, 0x00009B85), ‘19000101’)
  417. GO
  418. – Result: 2009-01-02 00:00:00.000
  419. – SQL time part – right 4 bytes – milliseconds since midnight
  420. – 1000/300 is an adjustment factor
  421. – SQL dateadd to Midnight
  422. SELECT Now=DATEADD(MS, (1000.0/300)* CONVERT(BIGINT, 0x0122092D), ‘2009-01-02′)
  423. GO
  424. – Result: 2009-01-02 17:35:59.290
  425. ————
  426. ————
  427. – String date and datetime date&time columns usage
  428. – SQL Server datetime formats in tables
  429. ————
  430. USE tempdb;
  431. SET NOCOUNT ON;
  432. – SQL Server select into table create
  433. SELECT TOP (5)
  434. FullName=convert(nvarchar(50),FirstName+‘ ‘+LastName),
  435. BirthDate = CONVERT(char(8), BirthDate,112),
  436. ModifiedDate = getdate()
  437. INTO Employee
  438. FROM AdventureWorks.HumanResources.Employee e
  439. INNER JOIN AdventureWorks.Person.Contact c
  440. ON c.ContactID = e.ContactID
  441. ORDER BY EmployeeID
  442. GO
  443. – SQL Server alter table
  444. ALTER TABLE Employee ALTER COLUMN FullName nvarchar(50) NOT NULL
  445. GO
  446. ALTER TABLE Employee
  447. ADD CONSTRAINT [PK_Employee] PRIMARY KEY (FullName )
  448. GO
  449. /* Results
  450. Table definition for the Employee table
  451. Note: BirthDate is string date (only)
  452. CREATE TABLE dbo.Employee(
  453. FullName nvarchar(50) NOT NULL PRIMARY KEY,
  454. BirthDate char(8) NULL,
  455. ModifiedDate datetime NOT NULL
  456. )
  457. */
  458. SELECT * FROM Employee ORDER BY FullName
  459. GO
  460. /* Results
  461. FullName BirthDate ModifiedDate
  462. Guy Gilbert 19720515 2009-01-03 10:10:19.217
  463. Kevin Brown 19770603 2009-01-03 10:10:19.217
  464. Rob Walters 19650123 2009-01-03 10:10:19.217
  465. Roberto Tamburello 19641213 2009-01-03 10:10:19.217
  466. Thierry D’Hers 19490829 2009-01-03 10:10:19.217
  467. */
  468. – SQL Server age
  469. SELECT FullName, Age = DATEDIFF(YEAR, BirthDate, GETDATE()),
  470. RowMaintenanceDate = CAST (ModifiedDate AS varchar)
  471. FROM Employee ORDER BY FullName
  472. GO
  473. /* Results
  474. FullName Age RowMaintenanceDate
  475. Guy Gilbert 37 Jan 3 2009 10:10AM
  476. Kevin Brown 32 Jan 3 2009 10:10AM
  477. Rob Walters 44 Jan 3 2009 10:10AM
  478. Roberto Tamburello 45 Jan 3 2009 10:10AM
  479. Thierry D’Hers 60 Jan 3 2009 10:10AM
  480. */
  481. – SQL Server age of Rob Walters on specific dates
  482. – SQL Server string to datetime implicit conversion with DATEADD
  483. SELECT AGE50DATE = DATEADD(YY, 50, ‘19650123’)
  484. GO
  485. – Result: 2015-01-23 00:00:00.000
  486. – SQL Server datetime to string, Italian format for ModifiedDate
  487. – SQL Server string to datetime implicit conversion with DATEDIFF
  488. SELECT FullName,
  489. AgeDEC31 = DATEDIFF(YEAR, BirthDate, ‘20141231’),
  490. AgeJAN01 = DATEDIFF(YEAR, BirthDate, ‘20150101’),
  491. AgeJAN23 = DATEDIFF(YEAR, BirthDate, ‘20150123’),
  492. AgeJAN24 = DATEDIFF(YEAR, BirthDate, ‘20150124’),
  493. ModDate = CONVERT(varchar, ModifiedDate, 105)
  494. FROM Employee
  495. WHERE FullName = ‘Rob Walters’
  496. ORDER BY FullName
  497. GO
  498. /* Results
  499. Important Note: age increments on Jan 1 (not as commonly calculated)
  500. FullName AgeDEC31 AgeJAN01 AgeJAN23 AgeJAN24 ModDate
  501. Rob Walters 49 50 50 50 03-01-2009
  502. */
  503. ————
  504. – SQL combine integer date & time into datetime
  505. ————
  506. – Datetime format sql
  507. – SQL stuff
  508. DECLARE @DateTimeAsINT TABLE ( ID int identity(1,1) primary key,
  509. DateAsINT int,
  510. TimeAsINT int
  511. )
  512. – NOTE: leading zeroes in time is for readability only!
  513. INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 235959)
  514. INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 010204)
  515. INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 002350)
  516. INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 000244)
  517. INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 000050)
  518. INSERT @DateTimeAsINT (DateAsINT, TimeAsINT) VALUES (20121023, 000006)
  519. SELECT DateAsINT, TimeAsINT,
  520. CONVERT(datetime, CONVERT(varchar(8), DateAsINT) + ‘ ‘+
  521. STUFF(STUFF ( RIGHT(REPLICATE(‘0’, 6) + CONVERT(varchar(6), TimeAsINT), 6),
  522. 3, 0, ‘:’), 6, 0, ‘:’)) AS DateTimeValue
  523. FROM @DateTimeAsINT
  524. ORDER BY ID
  525. GO
  526. /* Results
  527. DateAsINT TimeAsINT DateTimeValue
  528. 20121023 235959 2012-10-23 23:59:59.000
  529. 20121023 10204 2012-10-23 01:02:04.000
  530. 20121023 2350 2012-10-23 00:23:50.000
  531. 20121023 244 2012-10-23 00:02:44.000
  532. 20121023 50 2012-10-23 00:00:50.000
  533. 20121023 6 2012-10-23 00:00:06.000
  534. */
  535. ————