不明确的列名称'CustomerId'

时间:2013-11-08 17:10:03

标签: sql sql-server

我有以下代码 -

declare @userType int
declare @custIdOfUser int

select 
    @userType = UserTypeId, @custIdOfUser = CustomerId 
from 
    customers c with (nolock)
left outer join 
    Sites s with (nolock) on c.CustomerId = s.CustomerId 
left outer join 
    customers rc on rc.CustomerId = c.ResellerId 
where 
    c.[name] is not null 
    and (c.customerId is null or rc.CustomerId = c.CustomerId) 
    and c.IsActive != ''
    and (@userType = 1 OR @userType = 2 OR 
           (c.customerId in ((SELECT u.CustomerId, ur.RoleId 
                              FROM Users u
                              INNER JOIN UserRoles ur ON ur.UserId = u.UserId AND ur.RoleId = 39
                              INNER JOIN Customers c ON ur.CustomerId = c.CustomerID 
                              WHERE u.UserId = 28 or u.UserTypeId = 3 or u.UserTypeId = 4 
                                and c.customerId in 
                                    (SELECT c.CustomerId FROM Customers c 
                                     WHERE c.resellerId = u.CustomerId )))))

它给了我以下错误消息 -

  

Msg 116,Level 16,State 1,Line 10
  当子查询未与EXISTS一起引入时,只能在选择列表中指定一个表达式   Msg 207,Level 16,State 1,Line 3
  列名称无效' UserTypeId'。
  Msg 209,Level 16,State 1,Line 3
  不明确的列名称' CustomerId'。

1 个答案:

答案 0 :(得分:2)

  1.   

    不明确的列名'CustomerId'

    你得到这个是因为你选择了CustomerId而没有指定从哪个表中取出它。此列名存在于您的3个表(UserRolesSitesCustomers)上,其中一个您要加入两次(Customers cCustomers rc )。你应该使你的select语句更明确,例如。

    select 
      @custIdOfUser = c.CustomerId
    
  2.   

    无效的列名称'UserTypeId'

    您的任何表格中都不存在此列。

  3.   

    当未使用EXISTS

    引入子查询时,只能在选择列表中指定一个表达式

    - 因为你有这个:

    c.customerId in ((SELECT u.CustomerId, ur.RoleId 
    

    应该是这样的:

    c.customerId in ((SELECT u.CustomerId