如何将errror处理添加到此存储过程中?

时间:2017-04-29 14:30:38

标签: sql-server tsql

如果员工(服务器)没有为任何人服务,如何从此过程中打印错误消息? try - catch是阻止处理此问题的唯一方法吗?

我当时认为if / else条件测试后跟Print消息符合我的要求。

存储过程:

if OBJECT_ID('customers_served', 'u') is not null
    drop procedure customers_served;
go

create procedure customers_served
    @employee_id int
as 
    set nocount on;

    select 
        c.customer_id, c.cust_lastname, 
        (sum(c.cust_total_guests)) as total_guests
    from 
        customers c
    join 
        seating s on c.customer_id = s.customer_id
    join 
        table_assignment ta on s.table_id = ta.table_id
    join 
        employees e on ta.employee_id = e.employee_id
    where 
        @employee_id = e.employee_id
    group by 
        c.customer_id, c.cust_lastname;

/* if total_guests = 0 print message the employee has served 0 guests */

测试程序:

exec customers_served
        @employee_id = 5;

3 个答案:

答案 0 :(得分:1)

以下代码段可能会有所帮助:

declare @r int

select @r = (sum(c.cust_total_guests)) as  total_guests
from customers c
join seating s on c.customer_id = s.customer_id
join table_assignment ta on s.table_id = ta.table_id
join employees e on ta.employee_id = e.employee_id
where @employee_id = e.employee_id
group by c.customer_id, c.cust_lastname;

if @r = 0
begin
-- do what ever you wish
end
else
begin
select c.customer_id, c.cust_lastname, (sum(c.cust_total_guests)) as      
       total_guests
from customers c
join seating s on c.customer_id = s.customer_id
join table_assignment ta on s.table_id = ta.table_id
join employees e on ta.employee_id = e.employee_id
where @employee_id = e.employee_id
group by c.customer_id, c.cust_lastname;
end 
end

答案 1 :(得分:1)

我将您的脚本修改为此。

use dbServers;

if OBJECT_ID('customers_served', 'u') is not null
drop procedure customers_served;
go

create procedure customers_served
@employee_id    int
as 
set nocount on;

declare @totalGuests int;

set @totalGuests = (
 select(sum(c.cust_total_guests))
 from customers c
 join seating s on c.customer_id = s.customer_id
 join table_assignment ta on s.table_id = ta.table_id
 join employees e on ta.employee_id = e.employee_id
 where @employee_id = e.employee_id
)

if @totalGuests = 0 OR @totalGuests IS NULL
BEGIN
 print 'This server did not serve any guests'
END
else
BEGIN
 select @totalGuests AS 'total_quests'
END

/* test procedure*/
exec customers_served
@employee_id = 5;

答案 2 :(得分:0)

您可以在查询后简单地测试@@ ROWCOUNT以确定是否返回了任何结果,而不是双重查询,如果@@ ROWCOUNT = 0,则打印您的消息。