7

我正在使用 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

你如何检索表的模式名称?

谢谢你的帮助

4

2 回答 2

28

使用OBJECT_SCHEMA_NAME

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
于 2012-05-22T06:59:34.063 回答
4

根据 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_idOBJECT_SCHEMA_NAME(),如果想得到模式名就schema_idSCHEMA_NAME()

于 2012-05-22T06:40:16.180 回答