SQL-希望根据IF条件写入唯一的错误值

时间:2019-01-03 11:18:50

标签: sql sql-server if-statement error-handling conditional-statements

我正在处理大量数据并对其进行错误检查,以确保其遵循正确的格式。所以我创建了很多IF条件,到目前为止,我可以将许多条件组合在一起,但是只输出一种错误..或者我最终为每个条件编写了大量的代码,只是为了获得清晰的错误输出。

有没有一种方法可以将特定的错误输出字符串放入IF条件?

这是我的代码:

-- set the initial @IntHosp_SUM value
        SELECT @IntHosp_SUM = 0  

        -- Store the sum value to @IntHosp_SUM
        SELECT  @IntHosp_SUM =
            (
            (COALESCE (CASE WHEN @Int1_5hosp = 1 THEN COUNT (Int1_5) ELSE NULL END, 0)) + 
            (COALESCE (CASE WHEN @Int2_5hosp = 1 THEN COUNT (Int2_5) ELSE NULL END, 0)) + 
            (COALESCE (CASE WHEN @Int3_5hosp = 1 THEN COUNT (Int3_5) ELSE NULL END, 0)) + 
            (COALESCE (CASE WHEN @Int4_5hosp = 1 THEN COUNT (Int4_5) ELSE NULL END, 0)) + 
            (COALESCE (CASE WHEN @Int5_5hosp = 1 THEN COUNT (Int5_5) ELSE NULL END, 0)) + 
            (COALESCE (CASE WHEN @Int6_5hosp = 1 THEN COUNT (Int6_5) ELSE NULL END, 0))  
            ) 
        FROM    ASSSIST2_M0Teacher


        -- Check  RESUSE_SUM Value against Intervention Entries
        SELECT  @ErrorID = IsNull(Max(ErrorID) + 1, 1)
        FROM        ErrorTemp
        WHERE   (Quest = @DB + @Quest) AND (ValidateID = @ValidateID) 

        SELECT @Error = 0

        IF (@IntHosp_SUM = 1 and @Hosp1_info is null )
        or (@IntHosp_SUM = 2 and (@Hosp1_info is null or @Hosp2_info is null))
        or (@IntHosp_SUM >=3 and (@Hosp1_info is null or @Hosp2_info is null or @Hosp3_info is null))


        or (@IntHosp_SUM = 0 and (@Hosp1_info is not null or @Hosp2_info is not null or @Hosp3_info is not null ))
        or (@IntHosp_SUM = 1 and (@Hosp2_info is not null or @Hosp3_info is not null ))
        or (@IntHosp_SUM >= 2 and @Hosp3_info is not null)



            BEGIN   
            SELECT @Error = 1   
            END
            BEGIN 
            IF @Error = 1   
                INSERT INTO     ErrorTemp 
                        (Quest, 
                        ValidateID, 
                        ErrorID, 
                        ErrorType,
                        ErrorDesc,
                        Field)
                VALUES  (@DB + @Quest, 
                        @ValidateID, 
                        @ErrorID,
                        'Validation',       
                        'Too much or no info present, so incorrect',                                
                        'Hosp Info - admissions')                                       
            SELECT  @ErrorID = @ErrorID + 1
            END

我已经声明了所有变量以及它们在数据库中的位置,但是不想让多余的代码混乱。您可以看到,如果它们包含值1,我将对一系列字段求和。我不想添加任何其他值,仅添加那些带有“ 1”的值。

然后检查我的IF条件,如果总和为1,则只有一项。如果为2,则有两个条目..我们必须仔细检查其倒数,因此,如果总和为0,则不进行任何条目,依此类推。

是否可以将字符串从IF / OR条件传递到错误输出,以便我可以为每个条件编写唯一的错误?


SQL Server Management Studio 17.2

0 个答案:

没有答案