我正在使用SQL Server 2008并具有以下查询:
SELECT SO1.name AS Tab,
SC1.name AS Col,
SO2.name AS RefTab,
SC2.name AS RefCol,
FO.name AS FKName
FROM dbo.sysforeignkeys FK
INNER JOIN dbo.syscolumns SC1 ON FK.fkeyid = SC1.id AND FK.fkey = SC1.colid
INNER JOIN dbo.syscolumns SC2 ON FK.rkeyid = SC2.id AND FK.rkey = SC2.colid
INNER JOIN dbo.sysobjects SO1 ON FK.fkeyid = SO1.id
INNER JOIN dbo.sysobjects SO2 ON FK.rkeyid = SO2.id
INNER JOIN dbo.sysobjects FO ON FK.constid = FO.id
如何检索表的架构名称?
感谢您的帮助
答案 0 :(得分:26)
SELECT
OBJECT_SCHEMA_NAME(f.parent_object_id) AS TableNameSchema, -- this
OBJECT_NAME(f.parent_object_id) AS TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) AS ColumnName,
OBJECT_SCHEMA_NAME(f.referenced_object_id) AS ReferenceTableNameSchema,
OBJECT_NAME (f.referenced_object_id) AS ReferenceTableName,
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) AS ReferenceColumnName,
f.name AS ForeignKey
FROM
sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o ON o.OBJECT_ID = fc.referenced_object_id
答案 1 :(得分:3)
根据Sql Server 2008:
SELECT Object_name(f.parent_object_id)
AS
TableName,
Col_name(fc.parent_object_id, fc.parent_column_id)
AS ColumnName,
Object_name (f.referenced_object_id)
AS ReferenceTableName,
Col_name(fc.referenced_object_id, fc.referenced_column_id)
AS
ReferenceColumnName,
f.name
AS ForeignKey,
Quotename(Schema_name(f.schema_id)) + '.' + Quotename(
Object_name(f.parent_object_id)) AS
schemaname,
Quotename(Schema_name(o.schema_id)) + '.' + Quotename(
Object_name(f.referenced_object_id))
AS ReferenceSchemaName
FROM sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.objects AS o
ON o.OBJECT_ID = fc.referenced_object_id
如果想要根据object_id
了解架构名称,请使用OBJECT_SCHEMA_NAME()
,如果您想根据schema_id
获取架构名称,请使用SCHEMA_NAME()
。< / p>