Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 涉及同一表中多列的条件where语句_Sql Server_Tsql - Fatal编程技术网

Sql server 涉及同一表中多列的条件where语句

Sql server 涉及同一表中多列的条件where语句,sql-server,tsql,Sql Server,Tsql,我有三张桌子 表1: emp_id, code_1, code_2 code_1, code_2 emp_id, emp_ind 表2: emp_id, code_1, code_2 code_1, code_2 emp_id, emp_ind 表3: emp_id, code_1, code_2 code_1, code_2 emp_id, emp_ind 表2是一个查找表。我需要更新表3检查表2中表1的code\u 1和code\u 2 如果表2中的code\u 2为nul

我有三张桌子

表1:

emp_id, code_1, code_2
code_1, code_2
emp_id, emp_ind
表2:

emp_id, code_1, code_2
code_1, code_2
emp_id, emp_ind
表3:

emp_id, code_1, code_2
code_1, code_2
emp_id, emp_ind
表2是一个查找表。我需要更新表3检查表2表1
code\u 1
code\u 2

如果表2中的
code\u 2
null
,则检查
表1中的
code\u 1
表2是否匹配,如果
更新
表3中的
emp\u ind
Y

如果表2中的
code\u 1
null
,则检查
表1中的
code\u 2
表2中的
是否匹配,如果
更新
表3中的
emp\u ind
Y

如果
code\u 1
code\u 2
表2中都有值,检查表1中的
code 1
code 2
是否与表2的值匹配,如果
表3中的
更新
emp\u ind

是否有一种方法可以简单地执行此操作,而不是像下面这样进行检查:

Update table_3 t3
Set t3.emp_ind = 'Y'
Where exists (
    Select 1 from table1 t1
        Inner Join table2 t2 
        on t1.code_1 = t2.code_1
        Where t2.code_2 is null
        And t2.emp_id= t3.emp_id
    Union
    Select 1 from table1 t1
        Inner Join table2 t2 
        on t1.code_2 = t2.code_2
        Where t2.code_1 is null
        And t2.emp_id= t3.emp_id
    Union
    Select 1 from table1 t1
        Inner Join table2 t2 
        on t1.code_1 = t2.code_1
        And t1.code_2 = t2.code_2
        Where t2.emp_id= t3.emp_id
)

可以使用
运算符组合条件联接,如下所示:

Update table_3 t3
Set t3.emp_ind = 'Y'
Where exists (
    Select 1 from table1 t1
        Inner Join table2 t2 
        on 
           (t1.code_1 = t2.code_1 AND t2.code_2 is null)
        OR (t1.code_2 = t2.code_2 AND t2.code_1 is null)
        OR (t1.code_1 = t2.code_1 AND t1.code_2 = t2.code_2)
        Where t2.emp_id= t3.emp_id
)
表达式和应该允许您在
code_1
code_2
上的
Table1
Table2
之间使用一对
left-outer-join
确定
emp_ind
值。