SQL Server中获取表的主键和外键

create table Test 
( 
    T_RecordID uniqueidentifier not null primary key, 
    T_UserID nvarchar(10), 
) 
create table TestLine 
( 
    TL_RecordID uniqueidentifier not null primary key, 
    TL_T_RecordID uniqueidentifier not null references Test(T_RecordID), 
) 
 
--primary key(参考sp_pkeys): 
--exec sp_pkeys @table_name='TestLine' 
declare @tablename as nvarchar(30) 
set @tablename='TestLine' 
 
select column_name = convert(sysname,c.name)                
from sysobjects o 
join sysindexes i on i.id=o.id 
join syscolumns c on c.id=o.id                  
where o.id = object_id(@tablename)                                                               
and (i.status & 0x800) = 0x800                              
and (c.name = index_col (@tablename, i.indid,  1) or      
     c.name = index_col (@tablename, i.indid,  2) or      
     c.name = index_col (@tablename, i.indid,  3) or      
     c.name = index_col (@tablename, i.indid,  4) or      
     c.name = index_col (@tablename, i.indid,  5) or      
     c.name = index_col (@tablename, i.indid,  6) or      
     c.name = index_col (@tablename, i.indid,  7) or      
     c.name = index_col (@tablename, i.indid,  8) or      
     c.name = index_col (@tablename, i.indid,  9) or      
     c.name = index_col (@tablename, i.indid, 10) or      
     c.name = index_col (@tablename, i.indid, 11) or      
     c.name = index_col (@tablename, i.indid, 12) or      
     c.name = index_col (@tablename, i.indid, 13) or      
     c.name = index_col (@tablename, i.indid, 14) or      
     c.name = index_col (@tablename, i.indid, 15) or      
     c.name = index_col (@tablename, i.indid, 16)        
     ) 
 
--foreign key: 
select t1.name,t2.rtableName,t2.name  
from  
( 
    select col.name, f.constid as temp  
    from syscolumns col,sysforeignkeys f  
    where f.fkeyid=col.id  
    and f.fkey=col.colid  
    and f.constid in  
    (  
        select distinct(id)   
        from sysobjects  
        where object_name(parent_obj)=@tablename 
        and xtype='F'  
    )  
) as t1 
join 
( 
    select object_name(f.rkeyid) as rtableName,col.name,f.constid as temp  
    from syscolumns col,sysforeignkeys f  
    where f.rkeyid=col.id  
    and f.rkey=col.colid  
    and f.constid in  
    ( 
        select distinct(id)  
        from sysobjects  
        where object_name(parent_obj)=@tablename  
        and xtype='F'  
    )  
) as t2 on t2.temp=t1.temp 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值