April 13
Ottenere i nomi dei mesi in un intervallo di date è un compito molto meno complicato di quanto possa apparire a prima vista, anche se può essere fatto in modi leggermente diversi a seconda del sapore di SQL che si sta utilizzando. Con T-SQL può essere fatto con la funzione DATENAME e una variabile di tabella, mentre con MySQL si può usare la funzione MONTHNAME e una tabella temporanea.
1 Dichiarare la data di inizio e di fine delle variabili, così come una variabile di tabella per memorizzare temporaneamente i nomi dei mesi; per esempio:
DICHIARARE @Start DATETIME;
DICHIARARE @end DATETIME;
DICHIARARE @months TABELLA (month_name VARCHAR (30));
SET @Start = '2011-01-01';
SET @end = '2011-12-01';
2 Scorrere dei mesi, aggiungendo i nomi dei mesi alla variabile tabella utilizzando il DATENAME e funzioni DATEADD; per esempio:
DICHIARARE @Start DATETIME;
DICHIARARE @end DATETIME;
DICHIARARE @months TABELLA (month_name VARCHAR (30));
SET @Start = '2011-01-01';
SET @end = '2011-12-01';
WHILE (@Start <@end)
INIZIO
INSERT INTO @months
SELECT DATENAME(month, @start);
SET @Start = DATEADD (mese, 1, @Start);
FINE
3 Infine, selezionare l'elenco dei nomi dei mesi dalla variabile di tabella; per esempio:
DICHIARARE @Start DATETIME;
DICHIARARE @end DATETIME;
DICHIARARE @months TABELLA (month_name VARCHAR (30));
SET @Start = '2011-01-01';
SET @end = '2011-12-01';
WHILE (@Start <@end)
INIZIO
INSERT INTO @months
SELECT DATENAME(month, @start);
SET @Start = DATEADD (mese, 1, @Start);
FINE
SELECT * FROM @months;
4 Dichiarare le inizio e fine variabili di data, e quindi creare una tabella temporanea per contenere i nomi dei mesi; per esempio:
DICHIARARE @Start DATETIME;
DICHIARARE @end DATETIME;
CREATE TempMonths tabella temporanea (month_name VARCHAR (30));
SET @Start = '2011-01-01';
SET @end = '2011-12-01';
5 Scorrere dei mesi, aggiungendo i nomi dei mesi per la tabella temporanea utilizzando il MONTHNAME e funzioni DATE_ADD; per esempio:
DICHIARARE @Start DATETIME;
DICHIARARE @end DATETIME;
CREATE TempMonths tabella temporanea (month_name VARCHAR (30));
SET @Start = '2011-01-01';
SET @end = '2011-12-01';
WHILE (@Start <@end)
INIZIO
INSERT INTO TempMonths
SELECT MONTHNAME(@start);
SET @Start = DATE_ADD (@start, INTERVALLO 1 mese);
FINE
6 Infine, selezionare l'elenco dei nomi dei mesi e la pulizia della tabella temporanea; per esempio:
DICHIARARE @Start DATETIME;
DICHIARARE @end DATETIME;
CREATE TempMonths tabella temporanea (month_name VARCHAR (30));
SET @Start = '2011-01-01';
SET @end = '2011-12-01';
WHILE (@Start <@end)
INIZIO
INSERT INTO TempMonths
SELECT MONTHNAME(@start);
SET @Start = DATE_ADD (@start, INTERVALLO 1 mese);
FINE
SELECT * FROM TempMonths;
GOCCIA TempMonths tavola;