SELECT子查询中的IF / CASE语句

时间:2016-07-04 11:05:57

标签: sql if-statement subquery case

我的脚本几乎完美无缺,但下面的部分是导致我出现问题的唯一部分。当FSFSR表中存在记录时,这部分代码可以正常工作,但是如果不存在行我希望结果是 1 而不是SCFSR表中的MAX值+1但是我尝试了一切似乎不起作用。

(SELECT MAX(SCFSR.FSR_Num) FROM SCFSR WHERE SCFSR.FSR_Call_Num = T_Call_Num)+1

以下完整代码:

BEGIN TRY
BEGIN TRANSACTION
USE Tesseracttestv5

--------- DELCARE ARRAY ---------

DECLARE @RANGE TABLE(T_Call_Num INT);

INSERT @RANGE(T_Call_Num) VALUES (441925),(429021),(393852);

--------- SET CALL TO COMP ---------

UPDATE SCCall
SET
Call_Status = 'COMP',
Call_CDate = GETDATE()
WHERE Call_Num IN (SELECT T_Call_Num FROM @RANGE)

--------- INSERT SERVICE REPORT ---------

INSERT INTO SCFSR (FSR_Call_Num,    FSR_Call_Status,    FSR_Start_Date,     FSR_Complete_Date,  FSR_Last_Update, 
                   FSR_Symp_Code,   FSR_Fault_Code,     FSR_Rep_Code,       FSR_Solution,       FSR_User, 
                   FSR_Num,         FSR_Cost_Centre,    FSR_Site_Num,       FSR_Area_Code,      FSR_Employ_Num,
                   FSR_Prod_Num)

SELECT      T_Call_Num, 
            'COMP', GETDATE(), GETDATE(), GETDATE(), 'GEN', 'OPN', 0, 'Closed as part of database cleanse', 'JTY',
            (SELECT MAX(SCFSR.FSR_Num) FROM SCFSR WHERE SCFSR.FSR_Call_Num = T_Call_Num)+1,             
            (SELECT SCCall.Call_Cont_Num FROM SCCall WHERE SCCall.Call_Num = T_Call_Num),
            (SELECT SCCall.Call_Site_Num FROM SCCall WHERE SCCall.Call_Num = T_Call_Num),
            (SELECT SCCall.Call_Area_Code FROM SCCall WHERE SCCall.Call_Num = T_Call_Num),
            (SELECT SCCall.Call_Employ_Num FROM SCCall WHERE SCCall.Call_Num = T_Call_Num),
            (SELECT SCCall.Call_Prod_Num FROM SCCall WHERE SCCall.Call_Num = T_Call_Num)        
FROM @RANGE

COMMIT TRANSACTION
END TRY

BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION

SELECT  ERROR_NUMBER() AS ErrorNumber,
        ERROR_MESSAGE() AS ErrorMessage,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_LINE() AS ErrorLine
END CATCH

1 个答案:

答案 0 :(得分:1)

使用--skip-worktree

COALESCE

如果表中没有记录,则此子查询会使您COALESCE((SELECT MAX(SCFSR.FSR_Num) FROM SCFSR WHERE SCFSR.FSR_Call_Num = T_Call_Num)+1, 1) null将返回参数列表中的第一个非null元素。所以在这里,当记录不存在时,它会给你1个。