Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get table's schema name

I'm using SQL Server 2008 and have the following query:

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

How do you retrieve the table's schema name?

Thanks for your help

like image 986
Tom Schreck Avatar asked May 22 '12 06:05

Tom Schreck


2 Answers

Use 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
like image 70
gbn Avatar answered Oct 28 '22 06:10

gbn


As per 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 

If to want to know schema name on basis of object_id then use OBJECT_SCHEMA_NAME(), if you want to get schema name on basis of schema_id then use SCHEMA_NAME().

like image 42
Romil Kumar Jain Avatar answered Oct 28 '22 06:10

Romil Kumar Jain