简体   繁体   中英

CASE in SQL Server with multiple conditions

I am working in SQL Server to generate some results. I have two columns, Auth and DOB and three conditions to consider:

  1. Auth has Y then DOB will have date pf birth without any special character in the format yyyymmdd
  2. Auth has N and the age is less than or equal to 89 then we enter the DOB
  3. Auth has N and the age is more than 89 then we just enter the year 1900

The issue is since I am using DATE type for DOB, it's creating an issue for the the third condition since it is only in yyyy format.

This is the code that I am using

CASE 
   WHEN Auth IN ('Y', 'YES') 
      THEN CAST(REPLACE(DOB, '-', '') AS DATE)
   WHEN Auth IN ('N', 'NO') AND DATEDIFF(YEAR, DOB@TODAY) <= 89 
      THEN YEAR(DOB)
   WHEN Auth IN ('N', 'NO') AND DATEDIFF(YEAR, DOB@TODAY) > 89 
      THEN '1900'
   ELSE '' 
END AS BIRTHDATE

Can anyone please help me on how to do it with case itself?

Try this. It looks like you were getting a type clash in the second condition, which was returning an INT data type. Your statement said the second condition should return the DOB as is, which should be a VARCHAR data type to align with the other conditions of the CASE statement.

SELECT  CASE
            WHEN LEFT(Auth, 1) = 'Y' THEN FORMAT(DOB, 'yyMMdd')
            WHEN LEFT(Auth, 1) = 'N'
                 AND DATEDIFF(YEAR, DOB, @TODAY) <= 89 THEN CAST(DOB AS VARCHAR)
            WHEN LEFT(Auth, 1) = 'N'
                 AND DATEDIFF(YEAR, DOB, @TODAY) > 89 THEN '1900'
            ELSE ''
        END AS BIRTHDATE
FROM    dbo.children AS c;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM