t-sqlraiseerror

How to use RAISEERROR statement?


This is something very basic, but I can't understand it, and the manual is not helping:

declare @rule int =
    (select id from menu_availability_rules
        where (daily_serving_start = null or
            (daily_serving_start is null and null is null)) and
            (daily_serving_end = null or
            (daily_serving_end is null and null is null)) and
            (weekly_service_off = 3 or
            (weekly_service_off is null and 3 is null)) and
            (one_time_service_off = null or
            (one_time_service_off is null and null is null)));

        print @rule;
        -- syntax error here --\/
        if (@rule is not null) raiseerror ('test error', 42, 42);

        if @rule is not null
        begin
            delete from menu_availability
            where menu_id = 5365 and rule_id = @rule

            delete from menu_availability_rules
            where (daily_serving_start = null or
                (daily_serving_start is null and null is null)) and
                (daily_serving_end = null or
                (daily_serving_end is null and null is null)) and
                (weekly_service_off = 3 or
                (weekly_service_off is null and 3 is null)) and
                (one_time_service_off = null or
                (one_time_service_off is null and null is null))
            and not exists
                (select rule_id from menu_availability
                where rule_id = @rule)
        end

Why is it a syntax error? How would I write it? I need to throw error for debugging purposes, just to make sure the code reached the conditional branch.

I can just replace the raiseerror with select 1 / 0 and I will get what I need, but why can't I do it normally?


Solution

  • The correct name is RAISERROR.