sql >> Base de Datos >  >> RDS >> Sqlserver

Cómo mostrar la edad exacta en formato Año Mes Día en SQL Server

Hola Verifique la consulta a continuación.

--DROP TABLE patient
CREATE TABLE patient(PatName varchar(100),DOB date,  Age varchar(100))
INSERT INTO patient
VALUES('a','06/02/1947',NULL),('b','07/10/1947',NULL),('c','12/21/1982',NULL)

;WITH CTE(PatName,DOB,years,months,days) AS 
(SELECT PatName,DOB,DATEDIFF(yy,DOB,getdate()),DATEDIFF(mm,DOB,getdate()),DATEDIFF(dd,DOB,getdate()) FROM patient)

--SELECT * FROM CTE

SELECT PatName,DOB,
      CAST(months/12 as varchar(5))+' Years'+CAST((months % 12) as varchar(5))+' month/s '+CAST(CASE WHEN DATEADD(MM,(months % 12),DATEADD(YY,(months/12),DOB)) <= GETDATE() then DATEDIFF(dd,DATEADD(MM,(months % 12),DATEADD(YY,(months/12),DOB)),GETDATE()) ELSE DAY(getdate()) END as varchar(5))+' days' as Age

FROM CTE