Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Vari modi per utilizzare la funzione di data SQL CONVERT

In questo articolo esploreremo l'utilizzo dei diversi formati di data SQL CONVERT all'interno di SQL Server.

L'interpretazione della data varia tra i diversi paesi. Si supponga di disporre di un database SQL Server globale con una tabella che contiene un formato di data specifico. Ad esempio, ha una colonna di data che ha il valore 01/05/2020.

Come lo interpreti? Diamo un'occhiata alle seguenti interpretazioni nei diversi paesi.

  • USA:5 gennaio 2020 (formato standard – mm/gg/aaaa)
  • Europa:1 maggio 2020 (formato standard – gg/mm/aaaa)

Inoltre, altri paesi seguono formati di data diversi:

  • Turchia:gg.mm.aaaa
  • India:gg-mm-aaaa
  • Bulgaria:aaaa-m-g
  • Ungheria:aaaa.mm.gg.

Puoi fare riferimento a Wikipedia per ulteriori informazioni sui formati di data per paese.

Oltre a questo, a volte vogliamo anche includere il timestamp insieme alle date. Alcuni esempi di questo sono:

  • 05/01/2020 10:00
  • 05/05/2020 14:00
  • 05/00/2020 14:00
  • 05/01/2020 02:00:55

Non è possibile archiviare le date in una tabella di SQL Server in formati diversi, quindi abbiamo bisogno di un modo per convertire i formati di data. Esploriamo i diversi metodi di formato della data di SQL CONVERT.

Funzione di data SQL CONVERT

In genere, i professionisti del database utilizzano la funzione di data SQL CONVERT per ottenere le date in un formato specifico e coerente. Questo applica i codici di stile per date di output specifiche.

Sintassi della funzione CONVERT():

CONVERT(tipo di dati, data e ora [,stile])

Nella query SQL sottostante, convertiamo il datetime in due formati utilizzando la funzione CONVERT().

  • Formato mm/gg/aa:codice stile 1
  • Formato mm/gg/aaaa:codice stile 101
DECLARE @Inputdate datetime = '2019-12-31 14:43:35.863';
Select CONVERT(varchar,@Inputdate,1) as [mm/dd/yy],
CONVERT(varchar,@Inputdate,101) as [mm/dd/yyyy]

Allo stesso modo, possiamo specificare codici di stile diversi in modo da poter convertire le date nel formato richiesto.

SELECT '0' AS [StyleCode],
'Default format' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 0) AS [OutputFormat]
UNION ALL
SELECT '1' AS [StyleCode],
'USA - mm/dd/yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 1) AS [OutputFormat]
UNION ALL
SELECT '2' AS [StyleCode],
'ANSI - dd.mm.yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 2) AS [OutputFormat]
UNION ALL
SELECT '3' AS [StyleCode],
'British and French - dd/mm/yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 3) AS [OutputFormat]
UNION ALL
SELECT '4' AS [StyleCode],
'German - dd.mm.yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 4) AS [OutputFormat]
UNION ALL
SELECT '5' AS [StyleCode],
'Italian - dd-mm-yy ' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 5) AS [OutputFormat]
UNION ALL
SELECT '6' AS [StyleCode],
'Shortened month name -dd mon yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 6) AS [OutputFormat]
UNION ALL
SELECT '7' AS [StyleCode],
'Shortened month name - mon dd, yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 7) AS [OutputFormat]
UNION ALL
SELECT '8' AS [StyleCode],
'24 hour time -hh:mm:ss' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 8) AS [OutputFormat]
UNION ALL
SELECT '9' AS [StyleCode],
'Default + milliseconds - mon dd yyyy hh:mm:ss:mmmAM (or PM)' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 9) AS [OutputFormat]
UNION ALL
SELECT '10' AS [StyleCode],
'USA - mm-dd-yy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 10) AS [OutputFormat]
UNION ALL
SELECT '11' AS [StyleCode],
'Japan -yy/mm/dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 11) AS [OutputFormat]
UNION ALL
SELECT '12' AS [StyleCode],
'ISO format -yymmdd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 12) AS [OutputFormat]
UNION ALL
SELECT '13' AS [StyleCode],
'Europe default + milliseconds -dd mon yyyy hh:mm:ss:mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 13) AS [OutputFormat]
UNION ALL
SELECT '14' AS [StyleCode],
' 24 hour time with milliseconds -hh:mm:ss:mmm(24h)' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 14) AS [OutputFormat]
UNION ALL
SELECT '20' AS [StyleCode],
'ODBC canonical -yyyy-mm-dd hh:mm:ss(24h)' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 20) AS [OutputFormat]
UNION ALL
SELECT '21' AS [StyleCode],
'ODBC canonical (with milliseconds) -yyyy-mm-dd hh:mm:ss.mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 21) AS [OutputFormat]
UNION ALL
SELECT '22' AS [StyleCode],
'mm/dd/yy hh:mm:ss AM (or PM)' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 22) AS [OutputFormat]
UNION ALL
SELECT '23' AS [StyleCode],
'ISO 8601 - yyyy-mm-dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 23) AS [OutputFormat]
UNION ALL
SELECT '100' AS [StyleCode],
'mon dd yyyy hh:mmAM' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 100) AS [OutputFormat]
UNION ALL
SELECT '101' AS [StyleCode],
'USA -mm/dd/yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 101) AS [OutputFormat]
UNION ALL
SELECT '102' AS [StyleCode],
'ANSI -yyyy.mm.dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 102) AS [OutputFormat]
UNION ALL
SELECT '103' AS [StyleCode],
'British/French -dd/mm/yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 103) AS [OutputFormat]
UNION ALL
SELECT '104' AS [StyleCode],
'German - dd.mm.yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 104) AS [OutputFormat]
UNION ALL
SELECT '105' AS [StyleCode],
'Italian -dd-mm-yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 105) AS [OutputFormat]
UNION ALL
SELECT '106' AS [StyleCode],
'Shortened month name -dd mon yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 106) AS [OutputFormat]
UNION ALL
SELECT '107' AS [StyleCode],
'Shortened month name -mon dd, yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 107) AS [OutputFormat]
UNION ALL
SELECT '108' AS [StyleCode],
'24 hour time -hh:mm:ss' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 108) AS [OutputFormat]
UNION ALL
SELECT '109' AS
[StyleCode],
'Default + milliseconds -mon dd yyyy hh:mm:ss:mmmAM (or PM) ' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 109) AS [OutputFormat]
UNION ALL
SELECT '110' AS [StyleCode],
'USA -mm-dd-yyyy' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 110) AS [OutputFormat]
UNION ALL
SELECT '111' AS [StyleCode],
'JAPAN -yyyy/mm/dd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 111) AS [OutputFormat]
UNION ALL
SELECT '112' AS [StyleCode],
'ISO -yyyymmdd' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 112) AS [OutputFormat]
UNION ALL
SELECT '113' AS [StyleCode],
'Europe default + milliseconds -dd mon yyyy hh:mm:ss:mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 113) AS [OutputFormat]
UNION ALL
SELECT '114' AS [StyleCode],
' 24 hour time with milliseconds -hh:mm:ss:mmm(24h)' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 114) AS [OutputFormat]
UNION ALL
SELECT '120' AS [StyleCode],
'ODBC canonical- yyyy-mm-dd hh:mm:ss(24h)' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 120) AS [OutputFormat]
UNION ALL
SELECT '121' AS [StyleCode],
'ODBC canonical (with milliseconds) -yyyy-mm-dd hh:mm:ss.mmm' AS
[Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 121) AS [OutputFormat]
UNION ALL
SELECT '126' AS [StyleCode],
'ISO8601 -yyyy-mm-ddThh:mm:ss.mmm' AS [Standard and Format],
CONVERT(VARCHAR(50), Getdate(), 126) AS [OutputFormat]
UNION ALL
SELECT '127' AS [StyleCode],
'ISO8601 with time zone Z-yyyy-mm-ddThh:mm:ss.mmmZ' AS
[Standard and Format],
CONVERT(VARCHAR(100), Getdate(), 127) AS [OutputFormat]
UNION ALL
SELECT '131' AS [StyleCode],
'Arabic Hijri date - Islamic calendar' AS [Standard and Format],
CONVERT(VARCHAR(100), Getdate(), 131) AS [OutputFormat]

Nello screenshot qui sotto, puoi vedere il codice di stile, i loro standard, i formati e le date di output.

Convertire le date usando la funzione FORMAT()

Nella funzione CONVERT() sopra, ci viene richiesto di specificare i codici di stile per un output di formato specifico. Di solito, non vogliamo dover ricordare questi codici; pertanto, Microsoft ha introdotto la funzione FORMAT() in SQL Server 2012.

La sintassi è mostrata di seguito.

FORMAT (valore, formato [, cultura])

Valore :richiede un valore nel formato supportato. Puoi fare riferimento alla documentazione Microsoft per un elenco dettagliato.

Formato :Nel formato, possiamo specificare i codici di formato o il modello per nascondere i dati della data di input. Lo script seguente mostra i codici di formato, il modello e il formato di output.

DECLARE @InputDate DATETIME = '2020-12-08 15:58:17.643'
SELECT 'd' AS [FormatCode],
'Short Date Pattern' AS 'Pattern',
Format(@InputDate, 'd') AS 'Output'
UNION ALL
SELECT 'D' AS [FormatCode],
'Long Date Pattern' AS 'Pattern',
Format(@InputDate, 'D') AS 'Output'
UNION ALL
SELECT 'f' AS [FormatCode],
'Full Date/Time pattern (Short Time)' AS 'Pattern',
Format(@InputDate, 'f') AS 'Output'
UNION ALL
SELECT 'F' AS [FormatCode],
'Full Date/Time pattern (Long Time)' AS 'Pattern',
Format(@InputDate, 'F')
UNION ALL
SELECT 'g' AS [FormatCode],
'General Date/Time pattern (Short Time)' AS 'Pattern',
Format(@InputDate, 'g')
UNION ALL
SELECT 'G' AS [FormatCode],
'General Date/Time pattern (Long Time)' AS 'Pattern',
Format(@InputDate, 'G') AS 'Output'
UNION ALL
SELECT 'm' AS [FormatCode],
'Month/Day pattern' AS 'Pattern',
Format(@InputDate, 'm') AS 'Output'
UNION ALL
SELECT 'O' AS [FormatCode],
'Round trip Date/Time pattern' AS 'Pattern',
Format(@InputDate, 'O') AS 'Output'
UNION ALL
SELECT 'R' AS [FormatCode],
'RFC1123 pattern' AS 'Pattern',
Format(@InputDate, 'R') AS 'Output'
UNION ALL
SELECT 's' AS [FormatCode],
'Sortable Date/Time pattern' AS 'Pattern',
Format(@InputDate, 's') AS 'Output'
UNION ALL
SELECT 't' AS [FormatCode],
'Short Time pattern' AS 'Pattern',
Format(@InputDate, 't') AS 'Output'
UNION ALL
SELECT 'T' AS [FormatCode],
'Long Time Pattern' AS 'Pattern',
Format(@InputDate, 'T') AS 'Output'
UNION ALL
SELECT 'u' AS [FormatCode],
'Universal sortable Date/Time pattern' AS 'Pattern',
Format(@InputDate, 'u') AS 'Output'
UNION ALL
SELECT 'U' AS [FormatCode],
'Universal Full Date/Time pattern' AS 'Pattern',
Format(@InputDate, 'U') AS 'Output'
UNION ALL
SELECT 'Y' AS [FormatCode],
'Year Month pattern' AS 'Pattern',
Format(@InputDate, 'Y') AS 'Output'

Cultura :È un argomento facoltativo e definisce la cultura. Se non specifichiamo alcuna lingua, SQL Server utilizza la lingua della sessione corrente.

Nella query seguente, convertiremo un formato di data in una cultura specificata. Dobbiamo specificare il codice cultura. Ad esempio, il codice cultura per gli Stati Uniti è en-US e hi-IN è per l'India.

Gli script utilizzano la d codice di formato per modelli di date brevi.

DECLARE @d DATETIME ='2020-12-08 16:36:17.760';
SELECT FORMAT (@d, 'd', 'en-US') AS 'US English',
FORMAT (@d, 'd', 'no') AS 'Norwegian Result',
FORMAT(@d, 'd', 'hi-IN') AS 'India',
FORMAT(@d, 'd', 'ru-RU') AS 'Russian',
FORMAT(@d, 'd', 'gl-ES') AS 'Galician (Spain)',
FORMAT ( @d, 'd', 'en-gb' ) AS 'Great Britain English',
FORMAT (@d, 'd', 'zu') AS 'Zulu',
FORMAT ( @d, 'd', 'de-de' ) AS 'German',
FORMAT ( @d, 'd', 'zh-cn' ) AS 'Simplified Chinese (PRC)';

Ottieni il formato della data in una lingua specificata, come mostrato di seguito.

Se vuoi che l'output della data sia completo di data/ora (tempo lungo), specifica il codice formato F e cambierà rapidamente il formato della data.

Nel formato della data, puoi anche specificare i formati personalizzati e converte la stringa della data di input secondo le tue esigenze.

Per specificare le stringhe personalizzate, possiamo utilizzare le seguenti abbreviazioni.

  • dd:giorno del mese (da 01 a 31)
  • dddd:ortografia del giorno
  • MM:numero del mese (da 01 a 12)
  • MMMM:ortografia del mese
  • aa:anno a due cifre
  • aaaa:anno a quattro cifre
  • hh:Sono le 01:00 e le 12:00
  • HH:Sono disponibili 24 ore. formato ora da 00 a 23
  • mm:minuti da 00 a 59
  • ss:secondo da 00 a 59
  • tt:AM o PM

Nello script seguente, abbiamo convertito i formati della data di input in più formati utilizzando le abbreviazioni o i codici precedenti.

DECLARE @d DATETIME ='2020-12-08 16:36:17.760';
SELECT
FORMAT (@d,'dd/MM/yyyy ') as [Date Format 1] ,
FORMAT (@d, 'dd/MM/yyyy, hh:mm:ss ') as [Date Format 2] ,
FORMAT(@d,'yyyy-MM-dd HH:mm:ss')as [Date Format 3] ,
FORMAT(@d,'Dd MMM yyyy HH:mm:ss')as [Date Format 4] ,
FORMAT(@d,'MMM d yyyy h:mm:ss')as [Date Format 5] ,
FORMAT (@d, 'dddd, MMMM, yyyy')as [Date Format 6] ,
FORMAT (@d, 'MMM dd yyyy') as [Date Format 7] ,
FORMAT (@d, 'MM.dd.yy') as [Date Format 8] ,
FORMAT (@d, 'MM-dd-yy') as [Date Format 9] ,
FORMAT (@d, 'hh:mm:ss tt')as [Date Format 10] ,
FORMAT (@d, 'd-M-yy')as [Date Format 11] ,
FORMAT(@d,'MMMM dd,yyyy')as [Date Format 12]

Utilizzo di AT TIME ZONE in SQL Server 2016 o versioni successive

Paesi diversi seguono fusi orari diversi. Di solito, questi fusi orari seguono l'offset dall'ora UTC (Coordinated Universal Time). Alcuni esempi di fusi orari sono:

  • Ora legale dell'Australia centrale:UTC +10:30
  • Ora solare dell'India:UTC +5:30
  • Ora legale di montagna:UTC-6
  • Ora di Singapore:UTC+8
  • Ora legale centrale:UTC-5

Puoi fare riferimento a questo articolo per un elenco dettagliato dei fusi orari.

Molti paesi seguono l'ora legale e l'orologio viene regolato di 1 ora (o 30-45 minuti) a seconda dei fusi orari. Ad esempio, l'ora legale centrale ha seguito il programma seguente:

  • Ora standard iniziata:1 novembre 2020 02:00 ora locale. Gli orologi sono stati riportati indietro di un'ora.
  • L'ora standard termina il 14 marzo 2021 alle 02:00 ora locale. Gli orologi andranno avanti di un'ora.

SQL Server non è a conoscenza di questi fusi orari e dell'ora legale. Di solito, un'organizzazione segue le zone UTC in quanto non richiede alcuna modifica.

Come possiamo convertire i fusi orari in SQL Server?

È possibile utilizzare AT TIME ZONE a partire da SQL Server 2016 e convertire i fusi orari. Nella query seguente, mostra le date per l'ora solare centrale, l'ora solare dell'India e l'ora solare delle Samoa.

Declare @DateinUTC datetime2='2020-11-01 02:00:00'
select
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time' as 'Central Standard Time' ,
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'India Standard Time' as 'India Standard Time',
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Samoa Standard Time' as 'Samoa Standard Time',
@DateinUTC AT TIME ZONE 'UTC' AT TIME ZONE 'Dateline Standard Time' as 'Dateline Standard Time'

Per conoscere i fusi orari supportati, puoi eseguire una query su sys.time_zone_info  e restituisce il fuso orario e l'offset.

È quindi possibile filtrare i fusi orari che attualmente rispettano l'ora legale.

Select * from sys.time_zone_info where is_currently_dst=1

Consideriamo ora l'ora legale per l'ora di New York.

  • È iniziata l'ora legale:domenica 8 marzo 2020 alle 2:00.
  • L'ora legale è terminata domenica 1 novembre 2020 alle 2:00.

Converti la tua zona UTC nell'ora solare orientale e potrai notare l'impatto dell'ora legale.

DECLARE
@PreDST datetime = '2020-03-08 06:59:00',
@PostDST datetime = '2020-03-08 07:00:00';
SELECT
@PreDST AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time' AS [EST time before DST],
@PostDST AT TIME ZONE 'UTC' AT TIME ZONE 'Eastern Standard Time' AS [EST time before DST];

Punti utili per l'utilizzo dei formati di data SQL CONVERT

Valuta i requisiti della tua applicazione e scegli il tipo di dati appropriato data, SmallDateTime, DateTime, DateTime2 e DateTimeOffset.

È possibile convertire il formato della data utilizzando le funzioni SQL CONVERT date e FORMAT; tuttavia, è consigliabile utilizzare il formato che più si avvicina ai propri carichi di lavoro. Questo ti aiuterà a evitare di dover utilizzare la conversione esplicita della data.

È possibile tenere conto dell'ora legale in SQL Server utilizzando la funzione AT TIME ZONE a partire da SQL