create table tb(id int, name varchar(10), idnum int,户主 varchar(10))
insert into tb values(1 , '张三' , 434300 ,null);
insert into tb values(2 , '张三老婆', null ,null);
insert into tb values(3 , '张三女儿', null ,null);
insert into tb values(4 , '李四' , 434311 ,null);
insert into tb values(5 , '李四老婆', null ,null);
insert into tb values(6 , '李四儿子', null ,null);--使用游标前的数据
select * from tb
/*
id name idnum 户主
----------- ---------- ----------- ----------
1 张三 434300 NULL
2 张三老婆 NULL NULL
3 张三女儿 NULL NULL
4 李四 434311 NULL
5 李四老婆 NULL NULL
6 李四儿子 NULL NULL(所影响的行数为 6 行)
*/declare @id int,@idnum int;--有问题,
declare cur cursor fast_forward for
select id,idnum from tb;
open cur;
fetch next from cur into @id,@idnum;
while @@fetch_status=0
begin
if @idnum is not null
update tb set 户主 = '是' where id = @id
else
update tb set 户主 = '否' where id = @id
fetch next from cur into @id,@idnum;
end
close cur;
deallocate cur;
--使用游标后的数据
select * from tb
/*
id name idnum 户主
----------- ---------- ----------- ----------
1 张三 434300 是
2 张三老婆 NULL 否
3 张三女儿 NULL 否
4 李四 434311 是
5 李四老婆 NULL 否
6 李四儿子 NULL 否(所影响的行数为 6 行)
*/drop table tb
insert into tb values(1 , '张三' , 434300 ,null);
insert into tb values(2 , '张三老婆', null ,null);
insert into tb values(3 , '张三女儿', null ,null);
insert into tb values(4 , '李四' , 434311 ,null);
insert into tb values(5 , '李四老婆', null ,null);
insert into tb values(6 , '李四儿子', null ,null);--使用游标前的数据
select * from tb
/*
id name idnum 户主
----------- ---------- ----------- ----------
1 张三 434300 NULL
2 张三老婆 NULL NULL
3 张三女儿 NULL NULL
4 李四 434311 NULL
5 李四老婆 NULL NULL
6 李四儿子 NULL NULL(所影响的行数为 6 行)
*/declare @id int,@idnum int;--有问题,
declare cur cursor fast_forward for
select id,idnum from tb;
open cur;
fetch next from cur into @id,@idnum;
while @@fetch_status=0
begin
if @idnum is not null
update tb set 户主 = '是' where id = @id
else
update tb set 户主 = '否' where id = @id
fetch next from cur into @id,@idnum;
end
close cur;
deallocate cur;
--使用游标后的数据
select * from tb
/*
id name idnum 户主
----------- ---------- ----------- ----------
1 张三 434300 是
2 张三老婆 NULL 否
3 张三女儿 NULL 否
4 李四 434311 是
5 李四老婆 NULL 否
6 李四儿子 NULL 否(所影响的行数为 6 行)
*/drop table tb
-- 经典啥呢?SQL语句就能很容易处理的事情,用游标,就像是在用宰牛刀来宰鸡一样:大才小用!