【问题标题】:how to write a SQL procedure to print out message if no results are found如果没有找到结果,如何编写 SQL 过程以打印出消息
【发布时间】:2023-03-29 06:50:02
【问题描述】:

我正在编写一个程序来显示给定状态下的所有客户。用户将输入两个字符的缩写(exp:CA,PA),它将显示给定状态的所有客户。问题是,如果给定状态(如“GA”)没有客户,我需要打印一条消息。我在下面的工作是有效的,但我觉得可能有一种更简单/更有效的方法来做到这一点。欢迎任何反馈;我感到困惑的一个领域是如何清理我正在打印的信息。另外,请注意这是学校作业。

这是我迄今为止的程序:

    create procedure display_customer_state
(@state char (2))
as 
begin

--begin cursor
declare customer_state_check cursor for
select address_state
from customer
for read only

declare @entered_cust_state as char(2), @state_count as int 
set @state_count = 0
open customer_state_check
fetch customer_state_check into @entered_cust_state

    while @@FETCH_STATUS = 0
    begin

        if @entered_cust_state = @state
        begin
        set @state_count = @state_count+1
        end

fetch customer_state_check into @entered_cust_state

end
close customer_state_check
deallocate customer_state_check
--cursor end

if @state_count = 0
begin
print 'sorry, there are 0 customers in '
print @state
end

select first_name,last_name, primary_address, address_zip_code, address_state
from customer
where address_state = lower(@state)

end

【问题讨论】:

    标签: sql sql-server cursor procedure


    【解决方案1】:

    哎呀——您当然不需要游标来计算表中匹配过滤器的记录数。过滤后的计数应该能够替换整个游标:

    declare @state_count as int = 0;
    
    select @state_count = COUNT(numaddress_state)
    from customer
    where customer_state_check = @state;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多