SQL中的游标的编写 出现错误

来源:百度知道 编辑:UC知道 时间:2024/05/28 05:45:12
create table #tb1(
sale_id char(5) not null primary key,
tot_amt int,
ticheng int
)

declare @sale_id char(5)
declare @tot_amt int
declare @ticheng int

declare cur_sales cursor for
select sale_id,tot_amt from sales

open cur_sales
fetch cur_sales into @sale_id,@tot_amt
while @@fetch_status = 0

begin
if @tot_amt between 0 and 4000
set @ticheng= @tot_amt * 0.03
else
if @tot_amt between 4001 and 6000
set @ticheng=@tot_amt * 0.05
else
if @tot_amt between 6000 and 10000
set @ticheng=@tot_amt * 0.08
else
if @tot_amt between 10001 and 100000
set @ticheng=@tot_amt * 0.1
insert into #tb1 values(@sale_id,@tot_amt,@ticheng)
fetch cur_sales into @sale_id,@tot_amt
end

close cur_sales
deallocate cur_sales

select * from #tb1
drop table #tb1

出现 违反了 PRIMARY

PK是提示主键约束出现了错误,仔细检查你的游标编写时候有没有向表里录入或操作重复数据。

fetch cur_sales into @sale_id,@tot_amt 该句错误
应改为 fetch next from cur_sales into @sale_id,@tot_amt

table #tb1 设置sale_id主键,但在sales表中sale_id有重合