【问题标题】:Array within in clausein 子句中的数组
【发布时间】:2015-05-07 05:17:53
【问题描述】:

我有几个作为大型数据库脚本的一部分运行的 sql。经常有一些条件在几个 sql 上重复。例如

update phone_numbers set num = 'abc' where id not in (1,2,4,5,6,8);
update fax_numbers set num = 'abc' where id not in (1,2,4,5,6,8);
update email_add set val = 'abc' where id not in (1,2,4,5,6,8);

我的问题是我不断重复 not in 子句中的值。

如何将这些数字移动到变量中,然后应用于每个 sql。类似的东西

my_var = (1,2,4,5,6,8);
update phone_numbers set num = 'abc' where id not in @my_var;
update fax_numbers set num = 'abc' where id not in @my_var;
update email_add set val = 'abc' where id not in @my_var;

如果这有帮助,SQL 正在 Oracle 上运行?我以前用一个参数做过这个,但没有用一个数组。

我看过这个Oracle PL/SQL - How to create a simple array variable?,但这不适用于in

我已经搜索了几个地方,但似乎没有什么是我想要的

谢谢

【问题讨论】:

  • 您从哪里运行代码 - 只是一个客户端,如 SQL Developer 或 SQL*Plus?如果是,是哪个客户?
  • 您好,感谢您的回复。是通过 SQL plus 或 SQL 开发人员。谢谢

标签: sql oracle


【解决方案1】:

如果您使用的是 SQL*Plus 或 SQL Developer,您可以定义一个替换变量:

define my_var = '1,2,4,5,6,8'
update phone_numbers set num = 'abc' where id not in (&my_var);
update fax_numbers set num = 'abc' where id not in (&my_var);
update email_add set val = 'abc' where id not in (&my_var);

每个语句都会对值进行简单的替换(顾名思义);如果你有set verify on,那么你会看到这种情况发生:

old:update phone_numbers set num = 'abc' where id not in (&my_var)
new:update phone_numbers set num = 'abc' where id not in (1,2,4,5,6,8)

您还可以将语句包装在 PL/SQL 块中并使用 a built-in collection type 保存值:

declare
  my_var sys.odcinumberlist;
begin
  my_var := sys.odcinumberlist(1,2,4,5,6,8);

  update phone_numbers set num = 'abc'
  where id not in (select column_value from table (my_var));
  update fax_numbers set num = 'abc'
  where id not in (select column_value from table (my_var));
  update email_add set val = 'abc'
  where id not in (select column_value from table (my_var));
end;
/

...它更长并且隐藏更新计数,除非您自己显示 SQL%ROWCOUNT,但可以在任何客户端上工作。

因为这是使用可变数组类型,所以您可以使用集合方法。因此,如果您当前在 PL/SQL 块中有类似的内容::

if x in (1,2,4,5,6,8) then

你可以这样做;

if my_var.exists(x) the 

【讨论】:

  • 谢谢@Alex-poole。我已经开始工作了。由于某种原因,替代位似乎不起作用。它打开了一个弹出窗口,要求我输入数据。我尝试了内置的集合类型,除了我在 if 中使用条件之外,它对大多数人都有效。然后我不得不复制 if 语句的 id :(
  • @RNJ - 如果你运行了define 部分,你不应该得到一个弹出窗口。至少,作为脚本运行,并且在最近的版本中。不知道你所说的“如果”是什么意思,你能举个例子吗?
  • 是的,定义应该可以工作——我也看过其他网站。不知道发生了什么。 if 语句不允许子选择子句和集合类型,因为它正在从 table(..) 中进行选择,那么我认为它将它视为子选择
  • @RNJ - 如果我理解你在做什么,比如说,相当于if x in (&my_var) then(如果定义有效!),你可以使用收集方法:if my_var.exists(x) then。 (将其添加到我的答案中)。不知道为什么定义不起作用;您使用的是真正旧版本的 SQL Devleoper 吗?两者都可以在 SQL*Plus 中工作。
猜你喜欢
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 2014-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
相关资源
最近更新 更多