如果值不在表A中,则选择原始值

时间:2015-10-27 21:37:59

标签: sql sql-server tsql case-when

让我添加更详细的内容并重新解释我的问题,因为我在离开工作时匆匆写作:

首先是表格:

表A与表B具有1:1的关系

表A与TABLE XYZ(我们要更新的表)具有1:M的关系

我有一个名为sp_parent的存储过程,它调用另一个名为sp_update_child的存储过程(这样主要功能是更新表)

在我的sp_update_child中,我有一个像这样的变量集:

SET @trustee_variable_id = SELECT TOP 1 ID_A
                           FROM TABLE A
                           WHERE clause1 AND clause2 AND etc

它返回一个ID,让我们说3000

然后转到更新声明:

UPDATE TABLE_XYZ
SET TABLE_XYZ.trustee_id = (@trustee_variable_id = TABLE_XYZ.trustee_id`

但是,它无法更新,因为从表A中检索到的ID(3000)不在表B中,并且更新该特定列的唯一方法是ID 3000,如表B所示。

如果从表A中检索到的ID不在表B中,如何添加检查,然后使用已在trustee_id列中的原始ID更新TABLE_XYZ.trustee_id?

以下是我的剧本 - 不确定我是否朝着正确的方向前进:

UPDATE TABLE_XYZ 
SET @trustee_variable_id = CASE 
    WHEN @trustee_variable_id NOT IN (SELECT ID_A FROM TABLE_B)
        THEN (SELECT trustee_id FROM TABLE_XYZ WHERE clause1 = clause2)

有人能指出正确的方向吗?

3 个答案:

答案 0 :(得分:1)

如果我理解你的逻辑,那么.... Table_a和Table_b包含两个id(可能还有其他字段)。您要查找的那个,以及您要使用的那个。为了您的示例,id_a和id_b是您要查找的ID,我创建了一个名为return_id的列,其中包含您要放入要更新的表中的值。

我认为table_a可能如下所示:
id_a,return_id
1,10 2,20 4,40

table_b可能看起来像这样:
id_b,return_id
1,100
2,200
3,300
4,400

现在这里是sql:

declare @trustee_variable_id int = 3
select case 
    when 
        not exists  (select return_id from table_a where id_a=@trustee_variable_id ) then
        (select return_id from table_b where id_b=@trustee_variable_id)
    else
        (select return_id from table_a where id_a=@trustee_variable_id)
    end

由于table_a中不存在3,因此它会查看table_b以返回值300。

如果您使用declare @trustee_variable_id int = 2运行它,它将返回20,因为table_a

中存在2

上面的示例SQL是一个select语句,将其转换为更新:

update [SomeTable] set [SomeColumn] = case 
    when 
        not exists  (select return_id from table_a where id_a=@trustee_variable_id ) then
        (select return_id from table_b where id_b=@trustee_variable_id)
    else
        (select return_id from table_a where id_a=@trustee_variable_id)
    end

并且不要忘记更新语句末尾的WHERE子句,否则你将改变所有行;)除非你的意图。

答案 1 :(得分:1)

我确实对你的更新声明感到困惑,但我认为你的意思可能就是这个。

update table_xyz
set trustee_id = @trustee_variable_id 
where exists (
  select * from table_b where id_b = @trustee_variable_id
)

答案 2 :(得分:0)

让我给你一个选择陈述

select isnull(tableB.col, tableA,col) 
  from tableA 
  left join TableB 
    on tableB.col = tableA.col