【问题标题】:If else in SQL Server with multiple insert statements如果在 SQL Server 中使用多个插入语句,则为 else
【发布时间】:2020-03-20 07:38:39
【问题描述】:
select 
    din, driv_height, city, Driver_Addres_Posta_Code, DRIV_GENDER_ID 
from 
    driv_testing 

if DRIV_GENDER_ID IN ('M', 'F') 
begin
    insert into driv_success
end
else DRIV_GENDER_ID not in ('M', 'F')
begin 
    insert into error_logs (error_description) 
    values ('Gender fails')
end

我有一个源表driv_testing 和汇表driv_successerror_logs 表来记录不良记录。

如果DRIV_GENDER_ID IN ('M', 'F') 那么我想插入driv_success 否则插入error_logs 表中..

但上述查询出现错误。

【问题讨论】:

  • 嗨,欢迎来到 stackoverflow!你的问题问得不好,请阅读:stackoverflow.com/help/how-to-ask
  • 请用您正在使用的 DBMS(MySQL、SQL Server、Oracle 等)标记您的请求。为了回答 SQL 问题,通常需要了解 DBMS。

标签: sql-server tsql sql-insert case-when


【解决方案1】:

您尚未标记您的 DBMS,我无法识别您尝试应用的语法。但通常插入不同的表需要单独的语句。大致如下:

insert into driv_success (din)
select din
from driv_testing
where driv_gender_id in ('M', 'F');

insert into error_logs (din, error_description) 
select din, 'Gender fails'
from driv_testing
where driv_gender_id not in ('M', 'F');

【讨论】:

  • 其实我想有多个插入语句使用 if else 或 case when
  • 您正在选择表driv_testing 的所有行,然后您询问if DRIV_GENDER_ID IN('M','F')。这个条件指的是哪一行?您将不得不循环通过您的 driv_testing 行(如果您的 DBMS 提供此功能 - 您还没有告诉我们您正在使用哪个 DBMS)。但这可能会比我只使用两个插入语句的方法慢得多。
  • 我的要求是在天蓝色数据工厂复制活动中,如果记录良好,我想将源数据移动到两个表中(通过所有条件,例如性别必须是 M 或 F,并且邮政编码应遵循特定的字母数字格式)那么这些记录应该进入 driv_success 表,如果记录由于任何条件不匹配而失败,它应该进入 error_log 表并且应该一次发生。所以我想在复制活动源端使用 if else 查询语句而不是给出数据集指向到特定的表。
  • 在 SQL Server 中,您可以使用存储过程来循环查询结果(游标循环):stackoverflow.com/questions/11852782/…
猜你喜欢
  • 2016-08-07
  • 1970-01-01
  • 2012-11-29
  • 2012-03-19
  • 1970-01-01
  • 2018-03-20
  • 1970-01-01
  • 2016-06-09
  • 1970-01-01
相关资源
最近更新 更多