【问题标题】:sql/plsql - insert rows from source table to target with one column in target depending on another column in Source tablesql/plsql - 将行从源表插入到目标中,目标中的一列取决于源表中的另一列
【发布时间】:2018-01-29 11:56:38
【问题描述】:

我有一个要求,我必须将行(几百行)从一个表(比如源)插入到另一个表(比如目标)。但是目标中有一个列(例如错误列),其每行的值取决于源中的列(例如电子邮件)。 例如,如果 source.email 为空,则 target.error = 'no email'(硬编码)否则 target.error = others(硬编码)。要在目标表中填充的所有其他列都存在于源表中。插入行的有效方法是什么?

【问题讨论】:

  • select AllYourColumns, case when source.email==null then target.error='no email'(hardcoded) else target.error = others.(hardcoded) end from YourTable
  • 样本数据和预期结果会有所帮助。听起来你需要CASE expression
  • 为什么你认为你需要一个存储过程?

标签: sql oracle plsql


【解决方案1】:
1. insert into target select col1,col2, decode(email,null,'no 
   email','others') col4, col5 from source;

2  insert into target select col1,col2, case when email is null then 'no 
   email' else 'others' end col4 , col5 
    from source.

1 Decode- 函数的工作方式类似于 if else 子句

   decode(email,null,'no  email','others') 

可以写成

 if email is null then 'no  email' else 'others' end if

see hier

2.Case when子句与If else子句相似/相同

 insert into select 

当源和目标中的数据类型匹配时,语句从源复制数据并将其插入目标。

 Insert into target(col1,col2) select col1, col2 from source 

可以写成

   Insert into targert select col,col2 from source 

当目标只包含两列时

【讨论】:

  • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation would greatly improve its long-term value 通过展示为什么这是一个很好的解决问题的方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多