1、获取相关表的字段名
SELECT OBJECT_NAME(OBJECT_ID) 表名,name 字段名
FROM sys.columns
WHERE OBJECT_NAME(OBJECT_ID) IN ('table1','table2')
ORDER BY OBJECT_NAME(OBJECT_ID)
2、获取表tb_User的所有外键
select OBJECT_NAME(f.fkeyid) as ftableName, 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)='tb_User
and xtype='F'
)
3. 获取表非主外键的其他列
SELECT TABLENAME, COLUMNNAME, DATATYPE
FROM
(SELECT OBJECT_NAME(OBJECT_ID) TABLENAME,NAME COLUMNNAME, USER_TYPE_ID DATATYPE
FROM SYS.COLUMNS
WHERE IS_IDENTITY <> 1) A
WHERE A.COLUMNNAME NOT IN
(SELECT COL.NAME COLNAME
FROM SYSCOLUMNS COL,SYSFOREIGNKEYS F
WHERE F.FKEYID=COL.ID
AND F.FKEY=COL.COLID
AND F.CONSTID IN
(SELECT ID
FROM SYSOBJECTS
WHERE XTYPE = 'F'))
AND A.TABLENAME = 'tb_Order'
说明:syscolumns(别名sc)代表所有表的列(包含系统表),sysforeignkeys(别名sf)代表所有外键,sysobjects(别名so)代表所有对象(如 表、试图)。其中
object_name(sc.id)代表sc列所在的表格名称,不加object_name只是id号,sc.name代表列名,sc.colid代表列序号
object_name(sf.fkeyid)代表该外键依赖的主键所在表名,不加object_name只是id号,sf.fkey代表该外键所在表的索引号(第几列)
object_name(so.id)代表对象名(一般是表名),不加object_name代表id号