我正在编写一个程序来显示给定状态下的所有客户。用户将输入两个字符缩写(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
答案 0 :(得分:1)
Ouch - 您当然不需要游标来计算与表中的过滤器匹配的记录数。过滤后的计数应该能够替换整个游标:
declare @state_count as int = 0;
select @state_count = COUNT(numaddress_state)
from customer
where customer_state_check = @state;