sql-serversql-server-2008selectin-clause

SQL Server - IN clause with multiple fields


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

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

I'm using ms sql server 2008


I know this can be achieved with joins and exists, I just wanted to know if it could just be done with the IN clause.


Solution

  • Not the way you have posted. You can only return a single field or type for IN to work.

    From MSDN (IN):

    test_expression [ NOT ] IN 
        ( subquery | expression [ ,...n ]
        ) 
    
    subquery - Is a subquery that has a result set of one column. 
               This column must have the same data type as test_expression.
    
    expression[ ,... n ] - Is a list of expressions to test for a match. 
                           All expressions must be of the same type as 
                           test_expression.
    

    Instead of IN, you could use a JOIN using the two fields:

    SELECT U.* 
    FROM user U
      INNER JOIN userType UT
        ON U.code = UT.code
        AND U.userType = UT.userType