我在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”可以解决问题。
答案 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)
)
注意:
WITH (NOLOCK)
已弃用。将连接隔离更改为READ UNCOMMITTED或SNAPSHOT。