[目录]
测试表-test_v_hwhao1
测试数据
操作脚本
我想做一个类似功能,循环遍历一个表里面的数据,查询指定的用户名,如果存在,则跳过。如果不存在,则添加
declare
var_num number;
var_cointais number;
Name varchar2(100);
begin
--获取所有公司信息
for item in (
select * from test_v_hwhao1
) loop
Name := '测试老大哥';
--获取对应 Name 值有没有数据
select count(1) into var_num from test_v_hwhao1 where Name = Name;
--没有数据,则添加
if var_num = 0 then
insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
values('10',Name,sysdate,'','');
end if;
end loop;
--提交
commit;
end;
/
执行这个脚本后,我查询数据库,发现数据没变化
我百思不得起解,脚本执行没问题,逻辑也没有问题
原因
通过查询数据库表,发现数据并没有添加
添加数据的 sql 是这里
--没有数据,则添加
if var_num = 0 then
insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
values('10',Name,sysdate,'','');
end if;
可能是变量 var_num
的值为 0
但是我们通过 sql 来查询,值明明是 0 啊
select count(1) from test_v_hwhao1 where Name = '测试老大哥';
后来我发现,这样查也可以
select count(1) from test_v_hwhao1 where Name = Name;
就是因为我们定义的变量 Name
和数据库表字段 Name
重复导致的问题。
修改脚本
把之前的变量 Name
修改为 var_name
declare
var_num number;
var_cointais number;
var_name varchar2(100);
begin
--获取所有公司信息
for item in (
select * from test_v_hwhao1
) loop
var_name := '测试老大哥';
--获取对应 Name 值有没有数据
select count(1) into var_num from test_v_hwhao1 where Name = var_name;
--没有数据,则添加
if var_num = 0 then
insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
values('10',var_name,sysdate,'','');
end if;
end loop;
--提交
commit;
end;
/
结果
select * from test_v_hwhao1 order by NO
变量赋值扩展-通过查询赋值多个变量
declare
var_num number;
var_num1 number;
var_cointais number;
Name varchar2(100);
begin
Name := '测试老大哥-11';
--获取对应 Name 值有没有数据
select count(1),22 into var_num,var_num1
from test_v_hwhao1 where Name = Name;
--没有数据,则添加
if var_num1 = 22 then
insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
values('11',Name,sysdate,'','');
end if;
--提交
commit;
end;
/
结果
select * from test_v_hwhao1