SQL 列名称与 PL/SQL 变量名称相同 - 如何在 select 语句中完成此操作?

Ed *_*eal 3 oracle plsql

假设我有一张桌子:

create table foo (
  col_1     number;
  col_2     number;
);
Run Code Online (Sandbox Code Playgroud)

然后我有以下代码

declare
   col_1    number;
   col_2    number;
begin
   col_1 := 1;
   select col_2 into col_2 from foo where col_1 = col_1;
end;
Run Code Online (Sandbox Code Playgroud)

当然,这不会按预期工作。如何在不需要更改变量名称的情况下使其工作?

use*_*735 6

如果您对“无需更改变量名称”的定义足够自由,则可以。阅读神话般的PL/SQL 名称解析说:

如果标识符是在命名的 PL/SQL 单元中声明的,您可以使用单元(块、子程序或包)的名称限定其简单名称(其声明中的名称),使用以下语法:

unit_name.simple_identifier_name

以下示例将按20预期打印:

create table foo (a number, b number);

insert into foo values(1, 10);
insert into foo values(2, 20);
insert into foo values(3, 30);

begin
  <<bar>>
  declare
    a number;
    b number;
  begin
    a := 2;
    select b into bar.b from foo where a = bar.a;
    dbms_output.put_line(b);
  end;
end;
/
Run Code Online (Sandbox Code Playgroud)

变量名不会改变。相反,他们是嗯......更有资格:)

请注意以下不起作用:

begin
  declare
    a number;
    b number;
  begin
    a := 2;
    select foo.b into b from foo where foo.a = a;
    dbms_output.put_line(b);
  end;
end;
/
Run Code Online (Sandbox Code Playgroud)

由于优先规则a, -select语句中的非限定符被解释为列:

如果 SQL 语句引用的名称既属于列又属于局部变量或形式参数,则列名优先。