T-SQL错误 - 子查询返回的值超过1

时间:2012-12-05 22:47:05

标签: sql-server tsql syntax subquery

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

  

Msg 512,Level 16,State 1,Line 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”可以解决问题。

2 个答案:

答案 0 :(得分: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语句只处理不同的值。

答案 1 :(得分: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。