11

T-SQL の case ステートメント内でエラーを発生させることはできませんか? 私はいつもSQLケースステートメントに問題があります:/

    begin try
    declare @i int 
    --set @i = (select COUNT(1) from table_name)

    select Item_Num =
        CASE (select COUNT(1) from table_name)
            when 1 then (select Item_Num from table_name)
            when 0 then (raiserror('No records in database', 0, 0))
            ELSE (raiserror('Multiple records in database', 0, 0))
        END
    from table_name

    end try
    begin catch
        declare @errormsg nvarchar(1024),
                @severity int,
                @errorstate int;

        select @errormsg = error_message(),
                @severity = error_severity(),
                @errorstate = error_state();

        raiserror(@errormsg, @severity, @errorstate);
    end catch
4

4 に答える 4

1

コメントで言ったように、CASEステートメントの範囲外でチェックするフラグを単純に作成する方が簡単だと思います。次のようなもの:

--- code before the TRY...
BEGIN TRY
    DECLARE @i int 

    -- declare a variable to act as a flag
    DECLARE @my_flag as int

    -- than change your statement to simply fill the value of the flag 
    CASE (SELECT COUNT(1) FROM table_name)
         WHEN 1 THEN SET @my_flag = 1
         WHEN 0 THEN SET @my_flag = 0
         ELSE SET @my_flag = -1
     END

    IF (NOT @my_flag in (-1, 0))
    BEGIN
        SET @Item_Num = (SELECT Item_Num FROM table_name) -- consider a filter here
      END 
     ELSE
    BEGIN
        IF (-1 = @my_flag) RAISERROR('too many records', 0, 0)
        IF (0 = @my_flag) RAISERROR('no records', 0, 0) 
      END
END TRY
BEGIN CATCH 
    --- rest of the code goes here.... 
于 2014-05-14T15:57:18.573 に答える