在不同的列上显示所选表及其coulm_name

时间:2018-10-04 10:54:39

标签: sql sybase

我有两个表TMPTMP1,所以我想从syscolumns中选择并获取2个表的列名 我想要这样的结果

tablename columnname  tablename1 columnname1

Tmp         col1        TMP1         col1

Tmp         col2        TMP1         col2

这是我试图做的,这是错误的:

select sc.name , sc1.name
from syscolumns sc inner join syscolumns sc1
on( sc.id=sc1.id and sc.id=object_id('TMP1'))
where sc.id=object_id('TMP')

1 个答案:

答案 0 :(得分:1)

假设:

  • 这是Sybase ASE
  • 表的列数相同
  • 两个表中的列名相同

设置:

create table TMP (col1 int, col2 int)
go
create table TMP1(col1 iny, col2 int)
go

有两种方法可以做到这一点,但我们将调整给定的查询:

select  'TMP' as tablename,
        sc.name as columnname,
        'TMP1' as tablename1,
        sc1.name as columname1

        -- can't join syscolumns on 'id' because each table has a unique object id;
        -- only thing we have to join on is the similarly named columns

from    syscolumns sc
join    syscolumns sc1
on      sc.name = sc1.name

where   sc.id  = object_id('TMP')
and     sc1.id = object_id('TMP1')

order by sc.name
go

 tablename columnname tablename1 columname1
 --------- ---------- ---------- ----------
 TMP       col1       TMP1       col1
 TMP       col2       TMP1       col2

以上代码已在ASE 15.7 SP138数据服务器上进行了测试。