SQL Server ed ALM su database


Il blog di Alessandro Alpi
Archivio Posts
Anno 2018

Anno 2017

Anno 2016

Anno 2015

Anno 2014

Anno 2013

Anno 2012

Anno 2011

Anno 2010

Anno 2009

Anno 2008

Anno 2007

Anno 2006

Utile funzione sulle date

Navigando qua e là ho trovato questa funzione (weblogs.sqlteam.com/jeffs) che può essere molto utile per i calcoli sulle date. Molto spesso in fatti dobbiamo ricavarci l’ultimo giorno del mese precedente, l’ultimo giorno del mese e così via..
Questa funzione può essere una soluzione:

CREATE FUNCTION [dbo].[MDate](@Year int, @Month int, @Day int)

  RETURNS DATETIME

AS

  BEGIN

      /*

      MDate(Year(@Date),Month(@Date),1) -- the 1st day of the month

      MDate(Year(@Date),Month(@Date)+1,1)-1  -- the last day of the month

      MDate(Year(@Date),12,31) -- the last day of the year

      MDate(Year(@Date),Month(@Date)+6,1) -- the first day of the month six months from @Date.

      MDate(Year(@Date),Month(@Date),1)-1 -- last day of previous month

      */

 

      declare @d datetime;

      declare @dOut datetime;

      set @d = dateadd(year,(@Year - 1753),'1/1/1753');

      set @d = dateadd(month,@Month - 1,@d);

      set @dOut = dateadd(day,@Day - 1,@d)

 

      return @dOut

END

Ad esempio, voglio ricavare l’ultimo giorno del mese precedente rispetto alla data corrente:

declare @date
set @date = GETDATE()
SELECT MDate(year(@date),month(@date),1)-1

Tutto qui

Categoria: Transact-SQL
mercoledì, 10 mag 2006 Ore. 13.02
Statistiche
  • Views Home Page: 585.700
  • Views Posts: 1.043.018
  • Views Gallerie: 610.103
  • n° Posts: 484
  • n° Commenti: 273



















Copyright © 2002-2007 - Blogs 2.0
dotNetHell.it | Home Page Blogs
ASP.NET 2.0 Windows 2003