1

我在 SQL Server 中收到以下错误:

消息 512,级别 16,状态 1,第 18 行子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>>、>= 或子查询用作表达式时,这是不允许的。

我的代码如下:

DECLARE
@personNumber varchar(20),
@itemNumber varchar(20)


SET @personNumber = 'null'
SET @itemNumber = 'null'

SELECT      
    OU.UserID
    ,OU.Name
    ,IGWQ.itemNumber
    ,IG.itemName
    ,IGWQ.QuantityOnHand
FROM dbo.Table1 IGWQ 
INNER JOIN Table2 OU        ON  IGWQ.UserId = OU.UserId
INNER JOIN Table3 IG        ON  IGWQ.itemNumber = IG.itemNumber
WHERE IGWQ.userid IN (CASE  WHEN @personNumber = 'null' 
                            THEN (  SELECT DISTINCT 
                                        UserID 
                                    FROM Table2 WITH(NOLOCK) 
                                    WHERE [Role] = '01')
                            ELSE @personNumber
                            END)
AND IGWQ.itemNumber IN (CASE    WHEN @itemNumber = 'null'
                                THEN (  SELECT DISTINCT 
                                            itemNumber 
                                        FROM dbo.Table1 WITH(NOLOCK))
                                ELSE @itemNumber
                                END)

任何人都可以提出解决这个问题的方法吗?我认为使用“IN”可以解决问题。

4

2 回答 2

2

用它来修复其余部分:

WHERE ((@personNumber <> 'null' AND @personNumber = IGWQ.userid)
OR (@personNumber = 'null' AND IGWQ.userid IN (  SELECT  UserID 
                                    FROM Table2 WITH(NOLOCK) 
                                    WHERE [Role] = '01')
   ))

您不需要 DISTINCT,因为 IN 语句只处理不同的值。

于 2012-12-05T23:09:18.150 回答
0
WHERE (IGWQ.userid = @personNumber OR 
       @personNumber = 'NULL' and
       EXISTS (SELECT *
                 FROM Table2 t WITH (NOLOCK)
                WHERE t.[Role] = '01' AND t.UserID = IGWQ.userid)
  )
  AND (IGWQ.itemNumber = @itemNumber OR
       @itemNumber = 'NULL' and 
       EXISTS (SELECT *
                 FROM dbo.Table1 t WITH (NOLOCK)
                WHERE t.itemNumber = IGWQ.itemNumber)
  )

笔记:

  1. CASE 返回一个标量,它不能返回一个子查询(即集合)。
  2. WITH (NOLOCK)已弃用。将连接隔离更改为 READ UNCOMMITTED 或 SNAPSHOT。
于 2012-12-05T23:08:04.353 回答