
Este es una funcion que he creado que sirve para retornar un periodo a partir del ingreso de una fecha.
ejemplo de uso:
dbo.funcDatePart('semester',Fecha)
dbo.funcDatePart('quarter',Fecha)
dbo.funcDatePart('year',Fecha)
dbo.funcDatePart('month',Fecha)
para esta funcion me apoyo en la funcion que trae por defecto sqlserver "datepart"
y agrego el periodo de semestres.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
*nombre del esquema. nombre de la funcion
CREATE FUNCTION [dbo].[funcDatePart]
( *variable de entrada y tipo
@DateType varchar(10),
@Date Datetime
)
*tipo de variable que retornamos
RETURNS int
AS
BEGIN
DECLARE
*agregamos las variables que necesitemos para realizar la funcion
@Period int
SELECT @Period = (
CASE
WHEN @DateType = 'year' THEN datepart(year,@Date)
WHEN @DateType = 'month' THEN datepart(month,@Date)
WHEN @DateType = 'quarter' THEN datepart(quarter,@Date)
WHEN @DateType = 'semester' THEN
(CASE
WHEN datepart(month,@Date) between 1 and 6
THEN '1'
WHEN datepart(month,@Date) between 7 and 12
THEN '2'
END
)
ELSE
'0'
END)
*Retorno el valor
RETURN @Period
END