Criando a função
CREATE FUNCTION FN_HORA_TRABALHO (@DATA DATETIME, @CHAPA VARCHAR(30))
RETURNS @TABHORAS TABLE (MANHA VARCHAR(20), TARDE VARCHAR(20), TOTAL VARCHAR(20))
AS
BEGIN
DECLARE @HORAS TABLE (
CHAVE INT,
DATA DATETIME,
BATIDA INT
)
INSERT INTO @HORAS (CHAVE, DATA, BATIDA)
SELECT ROW_NUMBER() OVER(ORDER BY A.DATA DESC) AS CHAVE, A.DATA, A.BATIDA
FROM ABATFUN A WITH (NOLOCK)
WHERE A.DATA = @DATA
AND A.CHAPA = @CHAPA
INSERT INTO @TABHORAS (MANHA, TARDE, TOTAL)
SELECT
dbo.FN_HORA((SELECT BATIDA FROM @HORAS WHERE CHAVE = 2) - (SELECT BATIDA FROM @HORAS WHERE CHAVE = 1)),
dbo.FN_HORA(ISNULL(((SELECT BATIDA FROM @HORAS WHERE CHAVE = 4) - (SELECT BATIDA FROM @HORAS WHERE CHAVE = 3)), 0)),
dbo.FN_HORA(((SELECT BATIDA FROM @HORAS WHERE CHAVE = 2) - (SELECT BATIDA FROM @HORAS WHERE CHAVE = 1)) +
ISNULL(((SELECT BATIDA FROM @HORAS WHERE CHAVE = 4) - (SELECT BATIDA FROM @HORAS WHERE CHAVE = 3)), 0))
RETURN
END
Para utilizar faça
SELECT * FROM dbo.FN_HORA_TRABALHO('2016-02-26', '00037')
Gostou da dica? Comente e compartilhe
0 Comentários