>Il tipo di dato della data è un datatime ma l'orario è impostato
>di default a 00:00 quindi non ha alcuna importanza ai fini della
>mia ricerca.
Bene.
>Dato in input la data del 15-02-2008 devo andare a recuperare
>tutte le informazioni relative alla prima data precedente rispetto
>a quella passata in input.
OK, osserva il seguente esempio:
USE tempdb;
CREATE TABLE dbo.MyTable(
Cod int NOT NULL PRIMARY KEY,
ValoreA char(1) NOT NULL,
ValoreB char(1) NOT NULL,
ValoreC char(1) NOT NULL,
ValoreD char(1) NOT NULL,
DataValuta datetime NOT NULL
);
INSERT dbo.MyTable VALUES(1, 'A', 'B', 'C', 'D', '20080101');
INSERT dbo.MyTable VALUES(2, 'E', 'R', 'T', 'Y', '20080202');
INSERT dbo.MyTable VALUES(3, 'L', 'K', 'J', 'W', '20080401');
SELECT TOP 1 *
FROM dbo.MyTable
WHERE DataValuta < '20080215'
ORDER BY DataValuta DESC;
/* Output:
Cod ValoreA ValoreB ValoreC ValoreD DataValuta
----------- ------- ------- ------- ------- -----------------------
2 E R T Y 2008-02-02 00:00:00.000
(1 row(s) affected)
*/
DROP TABLE dbo.MyTable;
Per non dare adito a fraintendimenti, è opportuno formattare la data seguendo lo standard ANSI SQL 'YYYYMMDD', quindi il tuo 15-02-2008 diventerà '20080215'.
A questo punto è sufficiente filtrare le righe considerando tutte quelle antecedenti a tale data, ordinandole in modo decrescente per data e restituendo la prima occorrenza.
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org