如果value不在TableA中,则select原始值

If value is not in Table A, then select original value

让我添加更详细的内容并重新表述我的问题,因为我在下班时匆忙写了它:

首先是 tables:

TABLE A 与 TABLE B

有 1:1 关系

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

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

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

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

它returns一个ID,比方说3000

然后进入更新语句:

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

但是,它无法更新,因为从 TABLE A 检索到的 ID 3000 不在 TABLE B 中,更新该特定列的唯一方法是如果 ID 3000 位于TABLE B.

我如何添加一个检查来说明,如果从 TABLE A 中检索到的 ID 不在 TABLE B 中,则使用已经存在的原始 ID 更新 TABLE_XYZ.trustee_id 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)

谁能指出正确的方向?

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

我假设 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 到 return 300 的值。

如果你 运行 它与 declare @trustee_variable_id int = 2 它将 return 20 因为 2 存在于 table_a

上面的例子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 子句,否则您将更改所有行 ;) 除非那是您的意图。

让我给你 select 声明

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

我肯定对你的更新声明感到困惑,但我想你可能是这个意思。

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