1

Need help... the following query gives an error when trying to use IF Else. The SERIAL_NUMBER field has the two digit year in it and I want to extract it and display it as a 4 digit year in it's own field.

SELECT 
   [START_TIMESTAMP]
  ,[END_TIMESTAMP]
  ,[SERIAL_NUMBER]
  ,[MODEL]
  ,[TESTING_ACTION_RESULT]
  ,[FAILED_STEP]
  ,[DISPOSITION]
  ,[TesterId]
  ,[Location]
  ,[Customer]
  ,IF CAST(substring([SERIAL_NUMBER],3,2)AS INT)>90
    '19'+substring([SERIAL_NUMBER],3,2) AS MFG_YYYY
   ELSE
    '20'+substring([SERIAL_NUMBER],3,2) AS MFG_YYYY
FROM [DATABASE_1].[dbo].[TBL_Unit_Test]
GO    

2 Answers 2

1

You cannot use an IF in a SELECT statement, instead you will use a CASE expression:

SELECT 
   [START_TIMESTAMP]
  ,[END_TIMESTAMP]
  ,[SERIAL_NUMBER]
  ,[MODEL]
  ,[TESTING_ACTION_RESULT]
  ,[FAILED_STEP]
  ,[DISPOSITION]
  ,[TesterId]
  ,[Location]
  ,[Customer]
  ,case 
    when CAST(substring([SERIAL_NUMBER],3,2)AS INT)>90
    then '19'+substring([SERIAL_NUMBER],3,2)
    else '20'+substring([SERIAL_NUMBER],3,2) end AS MFG_YYYY
FROM [DATABASE_1].[dbo].[TBL_Unit_Test]
Sign up to request clarification or add additional context in comments.

Comments

0

You can use CASE expression, like

SELECT 
   [START_TIMESTAMP]
  ,[END_TIMESTAMP]
  ,[SERIAL_NUMBER]
  ,[MODEL]
  ,[TESTING_ACTION_RESULT]
  ,[FAILED_STEP]
  ,[DISPOSITION]
  ,[TesterId]
  ,[Location]
  ,[Customer]
  , MFG_YYYY =
   CASE 
    WHEN CAST(substring([SERIAL_NUMBER],3,2)AS INT)>90 
       THEN '19'+substring([SERIAL_NUMBER],3,2)
    ELSE '20'+substring([SERIAL_NUMBER],3,2)
   END
FROM [DATABASE_1].[dbo].[TBL_Unit_Test]
GO   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.