1

需要帮助...以下查询在尝试使用 IF Else 时出错。SERIAL_NUMBER 字段中有两位数的年份,我想提取它并在它自己的字段中将其显示为 4 位数的年份。

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    
4

2 回答 2

1

您不能在 SELECT 语句中使用 IF,而是使用CASE表达式:

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]
于 2013-10-04T21:10:38.600 回答
0

你可以使用CASE expression,比如

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   
于 2013-10-04T21:12:05.827 回答