Home Page Home Page Tips & Tricks Che formato devo utilizzare per la definizione delle date in SQL Server ?

Che formato devo utilizzare per la definizione delle date in SQL Server ?


Il metodo più corretto per gestire le date in SQL Server consiste nel definire un campo datetime o smalldatetime, popolarlo specificando una data nel formato stringa 'YYYYMMDD' e leggerlo formattandolo nel modo desiderato ricorrendo alla funzione CONVERT.
Per maggiorni informazioni ti suggerisco di leggere attentamente i seguenti articoli di Kalen Delaney apparsi sui numeri di Settembre ed Ottobre 2000 di SQL Server Magazine:
http://www.sqlmag.com/Articles/Index.cfm?ArticleID=9147 
http://www.sqlmag.com/Articles/Index.cfm?ArticleID=9723 

Per maggiori informazioni sull'utilizzo delle funzioni CAST e CONVERT leggi il paragrafo CAST and CONVERT sui Books Online

Vediamo un piccolo esempio:

Codice .NET n°1
USE tempdb
GO

/* Creo la tabella dbo.Students */
CREATE TABLE dbo.Students(
StudentID int NOT NULL IDENTITY PRIMARY KEY,
FirstName varchar(10) NOT NULL,
LastName varchar(10) NOT NULL,
BirthDate datetime NOT NULL
)
GO

/* Inserisco qualche studente */
INSERT dbo.Students VALUES('Lorenzo', 'Benaglia', '19710612')
INSERT dbo.Students VALUES('Luca', 'Bianchi', '19731214')
INSERT dbo.Students VALUES('Gianluca', 'Hotz', '19710326')
INSERT dbo.Students VALUES('Andrea', 'Montanari', '19771105')
GO

/* Recupero gli studenti nati dal 1 gennaio 1971 al 31 dicembre 1973
** senza formattazione */

SELECT *
FROM dbo.Students
WHERE BirthDate BETWEEN '19710101' AND '19731231'

/* Output:

StudentID FirstName LastName BirthDate
----------- ---------- ---------- ------------------------
1 Lorenzo Benaglia 1971-06-12 00:00:00.000
2 Luca Bianchi 1973-12-14 00:00:00.000
3 Gianluca Hotz 1971-03-26 00:00:00.000

(3 row(s) affected)

*/

GO

/* Leggo le stesse righe formattando le date come DD/MM/YYYY */
SELECT StudentID, FirstName, LastName,
CONVERT(char(10), BirthDate, 103) Birthdate
FROM dbo.Students
WHERE BirthDate BETWEEN '19710101' AND '19731231'

/* Output:

StudentID FirstName LastName Birthdate
----------- ---------- ---------- ----------
1 Lorenzo Benaglia 12/06/1971
2 Luca Bianchi 14/12/1973
3 Gianluca Hotz 26/03/1971

(3 row(s) affected)

*/

GO

/* Pulizia */
DROP TABLE dbo.Students
Copyright © dotNetHell.it 2002-2024
Running on Windows Server 2008 R2 Standard, SQL Server 2012 & ASP.NET 3.5