子查询返回的值超过1。当子查询跟随=,!=,<,< =,>,> =或用作表达式时不允许

时间:2014-07-10 12:44:31

标签: sql sql-server

我收到以下SQL错误并且不确定原因?

  

子查询返回的值超过1。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

我已将问题缩小到我的过程中的一个选择。

DECLARE @ApplicationName varchar(32)
,@Email varchar(128)
,@Password varchar(128)

SET @ApplicationName = 'PraxiProSite'
SET @Email = 'jn@gmail.com'
SET @Password = 'jn@gmail.com'

DECLARE @PracId int
   SET @PracId = 
   (
        SELECT 
            MU.PractitionerId 
        FROM 
            MembershipUser AS MU WITH(NOLOCK) 
            LEFT JOIN Practitioner AS Pr WITH(NOLOCK) ON Pr.PractitionerId = MU.PractitionerId 
            LEFT JOIN Person AS Pe WITH(NOLOCK) ON Pe.PersonId = Pr.PersonId
    )

SELECT @PracId

4 个答案:

答案 0 :(得分:3)

SET @PracId = 
   (
        SELECT Top 1
            MU.PractitionerId 
        FROM 
            MembershipUser AS MU WITH(NOLOCK) 
            LEFT JOIN Practitioner AS Pr WITH(NOLOCK) ON Pr.PractitionerId = MU.PractitionerId 
            LEFT JOIN Person AS Pe WITH(NOLOCK) ON Pe.PersonId = Pr.PersonId
    )

确保您在此处执行订单,以获得预期值

答案 1 :(得分:1)

实际上,您可以在没有子查询的情况下执行此操作。

SELECT Top(1) @PracId = MU.PractitionerId 
FROM MembershipUser AS MU WITH(NOLOCK) 
        LEFT JOIN Practitioner AS Pr WITH(NOLOCK) ON Pr.PractitionerId = MU.PractitionerId 
        LEFT JOIN Person AS Pe WITH(NOLOCK) ON Pe.PersonId = Pr.PersonId

如果您的最终查询是SELECT @PracId,那么您可能也不需要变量。

SELECT TOP(1) MU.PractitionerId 
FROM MembershipUser AS MU WITH(NOLOCK) 
        LEFT JOIN Practitioner AS Pr WITH(NOLOCK) ON Pr.PractitionerId = MU.PractitionerId 
        LEFT JOIN Person AS Pe WITH(NOLOCK) ON Pe.PersonId = Pr.PersonId

答案 2 :(得分:1)

我认为您忘记包含过滤器,例如:

SELECT 
  MU.PractitionerId 
FROM MembershipUser AS MU WITH(NOLOCK) 
LEFT JOIN Practitioner AS Pr WITH(NOLOCK) 
  ON Pr.PractitionerId = MU.PractitionerId 
LEFT JOIN Person AS Pe WITH(NOLOCK) ON Pe.PersonId = Pr.PersonId
WHERE MU.Email = @Email and /* whatever else you need */

但是,这仍然是最好的方法。您正在使用ASP.NET成员身份,对吧?您应该使用一堆存储过程来获取用户ID(否则您将无法比较密码,我希望),并在SQL中完成剩下的工作。

答案 3 :(得分:1)

我相信你也许会错过SELECT语句中的WHERE子句。因为您当前选择了MembershipUser

中的所有行
SET @PracId = 
(
    SELECT Top 1
        MU.PractitionerId 
    FROM 
        MembershipUser AS MU WITH(NOLOCK) 
        LEFT JOIN Practitioner AS Pr WITH(NOLOCK) ON Pr.PractitionerId = MU.PractitionerId 
        LEFT JOIN Person AS Pe WITH(NOLOCK) ON Pe.PersonId = Pr.PersonId
    WHERE .....
   (i.e. WHERE MU.email = @email
           AND MU.Application = @application)
)