请帮我纠正语法错误

时间:2015-03-31 18:02:56

标签: sql sql-server tsql

我在执行下面的查询时遇到错误。我做错了什么?

Msg 512,Level 16,State 1,Line 3 子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

select

     so.name 'Table Name'
    ,so.id 'Table ID'
     ,so.xtype
     ,sc.name 'Column Name'
     ,sc.id 'Column ID'
     ,sf.constid
     ,sf.fkeyid 'Object ID of the table with FOREIGN KEY'
     ,sf.rkeyid 'Referenced Table ID'
     ,(select o.name 'Referenced Table' 
    from sysforeignkeys f
     inner join sysobjects o
      on o.id=f.rkeyid
      where o.xtype='U') 

    from sysobjects so
   inner join syscolumns sc 
    on so.id=sc.id
      inner join sysforeignkeys sf
     on so.id=sf.fkeyid 
     where so.xtype='U'
    and (sc.name like 'SSN'
     OR sc.name LIKE 'ssn%'         
     OR sc.name LIKE 'ssn%'         
      OR sc.name LIKE '%_ssn%'          
    OR sc.name LIKE '_ocsecno'          
    OR sc.name LIKE 'Ssn%');

3 个答案:

答案 0 :(得分:1)

select so.name      [Table Name]
        ,so.id      [Table ID]
        ,so.xtype
        ,sc.name    [Column Name]
        ,sc.id      [Column ID]
        ,sf.constid
        ,sf.fkeyid  [Object ID of the table with FOREIGN KEY]
        ,sf.rkeyid  [Referenced Table ID]
        ,(select TOP 1 o.name 
          from sysforeignkeys f
          inner join sysobjects o on o.id=f.rkeyid
          where o.xtype='U') AS [Referenced Table]
from sysobjects so
inner join syscolumns sc     on so.id = sc.id
inner join sysforeignkeys sf on so.id = sf.fkeyid 
where so.xtype='U'
  and (   sc.name like 'SSN'  --<-- Two operator together "LIKE" and  "="
       OR sc.name LIKE 'ssn%'         
       OR sc.name LIKE 'ssn%'         
       OR sc.name LIKE '%_ssn%'          
       OR sc.name LIKE '_ocsecno'          
       OR sc.name LIKE 'Ssn%');

重要提示

Select中的子查询必须返回标量值,将TOP 1添加到子查询中,它应该修复错误。

也可以使用Square Brackets []作为列名而不是文字字符串。

答案 1 :(得分:1)

问题出在你的where条款

 .....
 where so.xtype='U'
    and (sc.name like 'SSN' -- Here you have a unwanted = or sc.name = 'SSN'
     OR sc.name LIKE 'ssn%'         
     OR sc.name LIKE 'ssn%'         
      OR sc.name LIKE '%_ssn%'          
    OR sc.name LIKE '_ocsecno'          
    OR sc.name LIKE 'Ssn%');

答案 2 :(得分:1)

我不认为你的子查询是正确的,因为它无法引用你的sysobjects别名“so”。试试这个。另外我认为你不需要这么长的where子句。

select so.name      [Table Name]
        ,so.id      [Table ID]
        ,so.xtype
        ,sc.name    [Column Name]
        ,sc.id      [Column ID]
        ,sf.constid
        ,sf.fkeyid  [Object ID of the table with FOREIGN KEY]
        ,sf.rkeyid  [Referenced Table ID]
        ,zz.name    [Reference Table]
from sysobjects so
inner join syscolumns sc     on so.id = sc.id
inner join sysforeignkeys sf on so.id = sf.fkeyid 

--Use a join here for the reference table column
inner join sysobjects zz     on zz.id = sf.rkeyid

where   so.xtype='U'
        AND(
            sc.name LIKE '%ssn%'
            OR sc.name LIKE '_ocsecno'
            )