IN()子句中的子查询导致错误

时间:2008-10-02 16:38:56

标签: sql-server subquery in-clause

我在SQL Server 2005上,我收到一个错误,我很确定不应该这样做。

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.

我正在关注示例#B on this MSDN链接。

我存储的proc代码如下。如果您要求,我可以为这篇文章简化它:

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

我已经检查过子查询的结果集与子查询结果与之比较的strSearchTypeCode之间没有数据类型不匹配。

我认为没有理由不这样做。如果您有任何线索,请告诉我。

3 个答案:

答案 0 :(得分:4)

尝试重新排列查询,以便布尔表达式出现在子选择内,例如

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

答案 1 :(得分:2)

我不知道你可以像这样使用IN子句中的CASE语句。我建议将这一点改写为:

WHERE strUserName = @strUserName AND (
   (@bitQuickSearch = 1 AND strSearchTypeCode = 'Quick')
   OR
   (strSearchTypeCode IN (SELECT strSearchTypeCode FROM tblAdvanceSearchTypes))
)

或者,如果你真的喜欢那里的风格:

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

一般情况下,如果@bitQuickSearch = 1,SQL应该足够智能,以便优化表格。但是,我只是确定查询计划(信任,但验证)。

答案 2 :(得分:2)

在我看来,这个SELECT:

SELECT strSearchTypeCode FROM tblAdvanceSearchTypes

返回多行,这就是你的问题。您可以将其重写为:

SELECT TOP 1 strSearchTypeCode FROM tblAdvanceSearchTypes