RS First Dynamics NAV Blog


...from NAV 3.60 to NAV 2013
Archivio Posts
Anno 2015

Anno 2014

Anno 2013

Anno 2012

Anno 2011

Anno 2010

Anno 2009

Anno 2008

Anno 2007

Gestire le date con sql server

 Articolo di Lorenzo Benaglia

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:

Solving the Datetime Mystery

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

Vediamo un piccolo esempio:

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

Categoria: Sql Server ALL
sabato, 28 apr 2007 Ore. 11.42

Messaggi collegati


Statistiche
  • Views Home Page: 451.082
  • Views Posts: 863.498
  • Views Gallerie: 0
  • n° Posts: 343
  • n° Commenti: 0
Copyright © 2002-2007 - Blogs 2.0
dotNetHell.it | Home Page Blogs
ASP.NET 2.0 Windows 2003