0

我在 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.

我正在关注 MSDN 链接上的示例#B。

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

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 之间没有数据类型不匹配。

我看不出为什么这不起作用。如果您有任何线索,请告诉我。

4

3 回答 3

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
于 2008-10-02T16:43:41.547 回答
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 应该足够智能以优化表。但是,我会检查查询计划以确保(信任,但验证)。

于 2008-10-02T16:42:28.833 回答
2

在我看来,这个选择:

SELECT strSearchTypeCode FROM tblAdvanceSearchTypes

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

SELECT TOP 1 strSearchTypeCode FROM tblAdvanceSearchTypes
于 2008-10-02T16:42:35.403 回答