Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Come visualizzare l'età esatta nel formato Anno Mese Giorno in SQL Server

Ciao Controlla la domanda qui sotto.

--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