2012-05-22 86 views
4

我使用的是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 

你如何檢索表的模式的名字嗎?

感謝您的幫助

+2

您正在使用已過時,僅用於向後兼容性的意見。一種方法是http://msdn.microsoft.com/en-us/library/bb326599(v=sql.90).aspx –

回答

21

使用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 
+0

感謝您的幫助 –

+0

我用這個來獲取數據庫中所有外鍵的列表。謝謝! – Zero3

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_NAME()

+2

青睞使用['QUOTENAME'](http://msdn.microsoft.com/ en-us/library/ms176114.aspx)而不是'[''+ ... +'']''。它會正確地將名稱中嵌入的'''字符加倍,使用+ ... +錯過。 –

+0

@Remus,爲此+1。 –

+0

@RemusRusana - 我想這個代碼'創建表#T ( \t南VARCHAR(100) ) 插入到#T(NAM)VALUES( 'ABC []高清') SELECT * FROM #T如果QUOTENAME (nam)像Quotename('abc [] def') drop table#t'並且不給我任何結果.... – Nilish