sql脚本中的语法不正确

时间:2016-09-23 22:58:46

标签: sql sql-server sql-server-2008

不确定我在这里做错了什么。

SELECT DISTINCT
  managername,
  username,
  UserStatus,
  Usertitle,
  Loginid,
  Server,
  DBName,
  Response,
  busjustify,
  Comments,
  dtaccessnoneed
FROM (SELECT
  username,
  UserStatus,
  Usertitle,
  Loginid,
  Server,
  DBName,
  Response,
  busjustify,
  Comments,
  dtaccessnoneed,
  workbkname
FROM tbldb2midtierresponse
WHERE username IS NOT NULL
AND username <> 'User Name') a
INNER JOIN (SELECT DISTINCT
  managername,
  workbkname
FROM tbldb2midtierresponse
WHERE managername NOT IN ('Mid Tier', 'User Access Management', 'Reporting Manager')
AND managername IS NOT NULL) b

INNER JOIN (SELECT
  username,
  UserStatus,
  Usertitle,
  Loginid,
  Server,
  DBName,
  Response,
  busjustify,
  Comments,
  dtaccessnoneed,
  workbkname
FROM tbldb2midtierresponse
WHERE username IS NOT NULL
AND username <> 'User Name/ID Owner') c
  ON b.workbkname = c.workbkname

我得到的错误是在最后一行。

请帮助我做错的地方是这个脚本吗?

Msg 102,Level 15,State 1,Line 8 &#39; workbkname&#39;。

附近的语法不正确

3 个答案:

答案 0 :(得分:1)

Simplfied:

select * 
from (select ...) a 
inner join  (select ... ) b -- [!] missing on x.attr = b.attr statement 
inner join (select ... ) c on b.workbkname = c.workbkname

你没有加入表b(没有指定公共属性)

答案 1 :(得分:0)

你需要添加

a.workbkname = b.workbkname

select distinct managername, username,UserStatus, Usertitle, Loginid,Server,DBName,Response,busjustify, Comments, dtaccessnoneed
from
(select username,UserStatus, Usertitle, Loginid,Server,DBName,Response,busjustify, Comments, dtaccessnoneed,workbkname from tbldb2midtierresponse 
where username is not null and username <> 'User Name' ) a
inner join 
(select distinct managername ,workbkname from tbldb2midtierresponse where managername not in ('Mid Tier','User Access Management','Reporting Manager') and managername is not null ) b
on a.workbkname = b.workbkname
inner join
(select username,UserStatus, Usertitle, Loginid,Server,DBName,Response,busjustify, Comments, dtaccessnoneed,workbkname from tbldb2midtierresponse where username is not null and username <> 'User Name/ID Owner' ) c
on b.workbkname = c.workbkname

答案 2 :(得分:0)

所以你实际上有几个问题。

  • 在表别名a&amp;之间缺少条件B'/ LI>
  • 缺少表别名用于从中提取列的表将通过不明确的列错误
  • 最后可能没有必要将内部联接回同一个表。

在您的代码中,您似乎正在让所有用户加入以确保workbkname还有一个不在Mid tier中的管理器...并且不为null。然后加入到让其他人在工作簿上工作......

我猜你实际上是在尝试让所有不是'用户名'或'用户名/ ID所有者'的用户拥有一个不在的管理员名称('中间层','用户访问管理','报告经理')。如果是这样,我会按如下方式进行:

SELECT DISTINCT
    a.managername
    ,a.username
    ,a.UserStatus
    ,a.Usertitle
    ,a.Loginid
    ,a.Server
    ,a.DBName
    ,a.Response
    ,a.busjustify
    ,a.Comments
    ,a.dtaccessnoneed
FROM
    tbldb2midtierresponse a
    LEFT JOIN tbldb2midtierresponse m
    ON a.workbkname  = m.workbkname
    AND m.managername NOT IN ('Mid Tier','User Access Management','Reporting Manager')
    AND m.managername IS NOT NULL
WHERE
    username IS NOT NULL
    AND username NOT IN ('User Name','User Name/ID Owner')
    AND m.username IS NOT NULL