【问题标题】:Trying understand function and why it gives this result尝试理解函数以及为什么它会给出这个结果
【发布时间】:2017-03-25 20:10:56
【问题描述】:

有人写了(他离开公司)以下函数:

Create function code_status
( p_code_id varchar, 
  p_daytime date, 
  p_status varchar);

  Select status into l_value from table1 where code_id=p_code_id and daytime=p_daytime;

  Return l_value;
  End;

并在下面的sql查询中使用:

Select code, daytime, status, code_status(code_id, daytime, status) from  table2 
where code_status(code_id, daytime, status) in ('act') and daytime = '12 Jan 2017'

当我从函数运行 select 查询以获取 code = 'f23' 的所有行时

Select code, code_id, daytime, status from table1 where code = 'f23';

结果如下:

Code   code_id  status   daytime
F23    123df     act     16 Jul 2016
F23    123df     stn     12 Jan 2017
F23    123df     act     15 Mar 2017

当我在下面运行查询时,它会给出以下结果:

Select code, daytime, code_id,status, code_status(code_id, daytime, status)  stat_funct 
from table2 
where code_status(code_id, daytime, status) in ('act') 
  and daytime = '12 Jan 2017' 
  and code='f23' 
Code   daytime      code_id   status    stat_funct 
F23    12 Jan 2017   123df     act      act   

现在我想了解这个函数的作用以及它在查询中的工作原理,为什么 stat_funct 是“act”?

【问题讨论】:

  • 不同的code没有多个相同的code_id,code只分配给一个code_id。
  • 可以因为 " and daytime = '12 Jan 2017' " 吗?
  • 这可能主要是效率低下,至少你是如何称呼它的——你实际上是在查询中将 table1 连接到 table2,但通过函数间接连接。未使用 p_status 值。您可能在两个表中都有重复的数据,但很难从其中一个表的样本中分辨出来。 stat_funct 只是来自table1 的状态值。 table2 中有什么内容?
  • 该函数是为所谓的“工作保障”而编写的 :) 抱歉,没办法。

标签: sql oracle plsql oracle11g


【解决方案1】:

它使用提供的参数抽象对table2status 字段的访问并将其命名为“code_status”。 table1 和 table2 具有相似架构的事实是巧合,但这确实意味着可以将函数替换为连接(这会执行得更好)。

创建它的原因大概是为了使其更易于在简单查询中使用(以避免连接),或者出于安全原因(所有对数据的访问都通过 SP,并且通过授予对 SP 的访问权限来处理安全性而不是表格 - 恕我直言,这是一种反模式)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2019-02-14
    • 2010-10-10
    相关资源
    最近更新 更多