Oracle 变量同名问题踩坑记+操作表脚本

2019年07月25日 17:38 · 阅读(155) ·

[目录]

测试表-test_v_hwhao1

测试数据

操作脚本

我想做一个类似功能,循环遍历一个表里面的数据,查询指定的用户名,如果存在,则跳过。如果不存在,则添加

  1. declare
  2. var_num number;
  3. var_cointais number;
  4. Name varchar2(100);
  5. begin
  6. --获取所有公司信息
  7. for item in (
  8. select * from test_v_hwhao1
  9. ) loop
  10. Name := '测试老大哥';
  11. --获取对应 Name 值有没有数据
  12. select count(1) into var_num from test_v_hwhao1 where Name = Name;
  13. --没有数据,则添加
  14. if var_num = 0 then
  15. insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
  16. values('10',Name,sysdate,'','');
  17. end if;
  18. end loop;
  19. --提交
  20. commit;
  21. end;
  22. /

执行这个脚本后,我查询数据库,发现数据没变化

我百思不得起解,脚本执行没问题,逻辑也没有问题

原因

通过查询数据库表,发现数据并没有添加

添加数据的 sql 是这里

  1. --没有数据,则添加
  2. if var_num = 0 then
  3. insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
  4. values('10',Name,sysdate,'','');
  5. end if;

可能是变量 var_num 的值为 0

但是我们通过 sql 来查询,值明明是 0 啊

  1. select count(1) from test_v_hwhao1 where Name = '测试老大哥';

后来我发现,这样查也可以

  1. select count(1) from test_v_hwhao1 where Name = Name;

就是因为我们定义的变量 Name 和数据库表字段 Name 重复导致的问题。

修改脚本

把之前的变量 Name 修改为 var_name

  1. declare
  2. var_num number;
  3. var_cointais number;
  4. var_name varchar2(100);
  5. begin
  6. --获取所有公司信息
  7. for item in (
  8. select * from test_v_hwhao1
  9. ) loop
  10. var_name := '测试老大哥';
  11. --获取对应 Name 值有没有数据
  12. select count(1) into var_num from test_v_hwhao1 where Name = var_name;
  13. --没有数据,则添加
  14. if var_num = 0 then
  15. insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
  16. values('10',var_name,sysdate,'','');
  17. end if;
  18. end loop;
  19. --提交
  20. commit;
  21. end;
  22. /

结果

  1. select * from test_v_hwhao1 order by NO

变量赋值扩展-通过查询赋值多个变量

  1. declare
  2. var_num number;
  3. var_num1 number;
  4. var_cointais number;
  5. Name varchar2(100);
  6. begin
  7. Name := '测试老大哥-11';
  8. --获取对应 Name 值有没有数据
  9. select count(1),22 into var_num,var_num1
  10. from test_v_hwhao1 where Name = Name;
  11. --没有数据,则添加
  12. if var_num1 = 22 then
  13. insert into test_v_hwhao1(No,Name,Opdate,ratio,opshares)
  14. values('11',Name,sysdate,'','');
  15. end if;
  16. --提交
  17. commit;
  18. end;
  19. /

结果

  1. select * from test_v_hwhao1