Search code examples
sql-serversubqueryin-clause

Subquery in an IN() clause causing error


I'm on SQL Server 2005 and I am getting an error which I am pretty sure should not be getting.

Msg 512, Level 16, State 1, Procedure spGetSavedSearchesByAdminUser, Line 8 Subquery
returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I am following the example# B on this MSDN link.

My stored proc code is as follows. I can simplify it for the sake of this post if you request so:

ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] 
    @strUserName varchar(50)  
    ,@bitQuickSearch bit = 0
AS

BEGIN

    SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName]
    FROM [tblAdminSearches] 

    WHERE 
        strUserName = @strUserName
        AND 
        strSearchTypeCode 
            IN (
                CASE @bitQuickSearch 
                WHEN 1 THEN 'Quick' 
                ELSE (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes) 
                END
            )

    ORDER BY strSearchName
END

I have checked there is no datatype mismatch between the resultset from the subquery and the strSearchTypeCode the subquery result is compared with.

I see no reason why this should not work. If you have any clues then please let me know.


Solution

  • Try rearranging the query so that the boolean expression occurs inside the subselect, e.g.

    ALTER PROCEDURE [dbo].[spGetSavedSearchesByAdminUser] 
        @strUserName varchar(50)  
        ,@bitQuickSearch bit = 0
    AS
    
    BEGIN
    
        SELECT [intSearchID] ,strSearchTypeCode ,[strSearchName]
        FROM [tblAdminSearches] 
    
        WHERE 
            strUserName = @strUserName
            AND 
            strSearchTypeCode 
                    IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes where @bitQuickSearch=0
                        UNION
                        SELECT 'Quick' AS strSearchTypeCode WHERE @bitQuickSearch=1)
    
        ORDER BY strSearchName
    END