Sometime a simple solution have even simpler solutions but we often do not practice it as we do not see value in it or find it useful. Well, today’s blog post is also about something which I have seen not practiced much in codes. We are so much comfortable with alternative usage that we do not feel like switching how we query the data.
I was going over forums and I noticed that at one place user has used following code to get Schema Name from ObjectID.
USE AdventureWorks2012
GO
SELECT s.name AS SchemaName, t.name AS TableName,
s.schema_id, t.OBJECT_ID
FROM sys.Tables t
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE t.name = OBJECT_NAME(46623209)
GO
Before I continue let me say I do not see anything wrong with this script. It is just fine and one of the way to get SchemaName from Object ID.
However, I have been using function OBJECT_SCHEMA_NAME to get the schema name. If I have to write the same code from the beginning I would have written the same code as following.
SELECT OBJECT_SCHEMA_NAME(46623209) AS SchemaName, t.name AS TableName,
t.schema_id, t.OBJECT_ID
FROM sys.tables t
WHERE t.name = OBJECT_NAME(46623209)
GO
Now, both of the above code give you exact same result. If you remove the WHERE condition it will give you information of all the tables of the database.
Now the question is which one is better – honestly – it is not about one is better than other. Use the one which you prefer to use. I prefer to use second one as it requires less typing. Let me ask you the same question to you – which method to get schema name do yo use? and Why?
Reference: Pinal Dave (http://blog.sqlauthority.com)












Second method is more understandable
agree with you… less typing..
Second method is definitely better as it requires less typing and keeps the script simple. However, at the end of the day, its a matter of choice :)
I have used similar query in application as Follows, and I felt it is more easier to maintain.
select s.name as SchemaName,t.name as TableName
from sys.tables T, sys.schemas S
where S.schema_id=T.schema_id
and T.name=’Customers’
In the spirit of less typing :)
SELECT SCHEMA_NAME(t.schema_id) AS SchemaName, t.name AS TableName,
t.schema_id, t.OBJECT_ID
FROM sys.tables t
WHERE t.name = OBJECT_NAME(46623209)
Excellent Roji!
Hi can I fetch data from a table if I have the OBJECT_ID of the table?