SQL Server - IN clause with multiple fields

后端 未结 8 698
野性不改
野性不改 2020-12-20 11:42

Is it possible to include in a IN clause multiple fields? Something like the following:

select * from user
where code, userType in ( select code         


        
相关标签:
8条回答
  • 2020-12-20 11:58

    How about this instead:

    SELECT user.* FROM user JOIN userType on user.code = userType.code AND user.userType = userType.userType
    
    0 讨论(0)
  • 2020-12-20 11:58
    select * from user
    where (code, userType) in ( select code, userType from userType );
    
    0 讨论(0)
  • 2020-12-20 11:59

    I don't think that query is quite portable,it would be safer to use something like

    select * from user
    where code in ( select code from userType ) and userType in (select userType from userType)
    
    0 讨论(0)
  • 2020-12-20 12:07

    Only with something horrific, like

    select * from user
    where (code + userType) in ( select code + userType from userType )
    

    Then you have to manage nulls and concatenating numbers rather than adding them, and casting, and a code of 12 and a usertype of 3 vs a code of 1 and a usertype of 23, and...

    So there ya go: a solution that doesn't use joins or exists.. and a bunch of reasons why you shouldn't use it ;)

    0 讨论(0)
  • 2020-12-20 12:09

    You could use a form like this:

    select * from user u
    where exists (select 1 from userType ut
                  where u.code = ut.code
                    and u.userType = ut.userType)
    
    0 讨论(0)
  • 2020-12-20 12:12

    I had to do something very similar but EXISTS didn't work in my situation. Here is what worked for me:

    UPDATE tempFinalTbl
    SET BillStatus = 'Non-Compliant'
    WHERE ENTCustomerNo IN ( SELECT DISTINCT CustNmbr
                 FROM tempDetailTbl dtl
                WHERE dtl.[Billing Status] = 'NEEDS FURTHER REVIEW'
                  AND dtl.CustNmbr = ENTCustomerNo 
                  AND dtl.[Service] = [Service]) 
      AND [Service] IN  ( SELECT DISTINCT [Service] 
                 FROM tempDetailTbl dtl
                WHERE dtl.[Billing Status] = 'NEEDS FURTHER REVIEW'
                  AND dtl.CustNmbr = ENTCustomerNo 
                  AND dtl.[Service] = [Service]) 
    

    EDIT: Now that I look, this is very close to @v1v3kn's answer

    0 讨论(0)
提交回复
热议问题