需要帮助从SQL 2005查询中删除过时的= * join运算符

时间:2017-07-09 11:22:07

标签: sql sql-server-2005

以下查询在SQL2012及更高版本中不再兼容。需要协助转换。

select distinct po.name , sc.name, sc2.name
from sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref, syscolumns sc2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1
  and sc2.id =* po.id and sc2.colid =* ref.fkey2;

2 个答案:

答案 0 :(得分:0)

=*这里的重点是,即使找不到sc2的记录,也会给出结果。因此,这绝对需要变成left join

select distinct po.name , sc.name, sc2.name
from (sysobjects fo, sysobjects po, sysforeignkeys fk, sysobjects oo
    , syscolumns sc, sysreferences ref)
left join syscolumns sc2
  on sc2.id = po.id and sc2.colid = ref.fkey2
where fo.xtype = 'F' and oo.name = @tab_name
  and po.id = fo.parent_obj and fo.id = fk.constid and oo.id = fk.rkeyid
  and sc.id = po.id and ref.constid = fk.constid and sc.colid = ref.fkey1;

为了便于阅读,我们更喜欢将其余的旧式交叉连接重写为内部连接。您已经看到旧式语法太难理解了。

答案 1 :(得分:-1)

尝试此查询 -

SELECT DISTINCT po.NAME
    ,sc.NAME
    ,sc2.NAME
FROM sysobjects fo
    ,sysobjects po
    ,sysforeignkeys fk
    ,sysobjects oo
    ,syscolumns sc
    ,sysreferences ref
    ,syscolumns sc2
WHERE fo.xtype = 'F'
    AND oo.NAME = @tab_name
    AND po.id = fo.parent_obj
    AND fo.id = fk.constid
    AND oo.id = fk.rkeyid
    AND sc.id = po.id
    AND ref.constid = fk.constid
    AND sc.colid = ref.fkey1
    AND sc2.id = Null -- sc2.id = * po.id 
    AND sc2.colid = Null -- sc2.colid = * ref.fkey2 

因为,

*= Left Outer Join 

=* Right Outer Join

并且在上面的查询中试图通过搜索Nulls的ID来实现相同的目的。

我希望它有效。