tags:

views:

34

answers:

1

I have a table (DB_TableInfo) in my DB like the following

TableId         Type
859374678        R
579845658        B
478625849        R
741587469        E
.
.
.

this table represents all tables in my DB. What I wanna do is to write a query to select tables of Type 'R', get their Id and return the Name of the table belonging to that Id (the TableName column is not available in the specified table)

Can anybody help me out?

I wanna write a query similar to this one!

SELECT TableID = OBJECT_NAME FROM [DB_TableInfo] WHERE Type = 'R' 
+1  A: 

From the mention of sys.objects and use of square brackets I assume you are on SQL Server.

You can use the object_name function.

SELECT OBJECT_NAME(TableID) /*Might match objects that aren't tables as well though*/
 FROM [DB_TableInfo] 
 WHERE Type = 'R' 

Or join onto sys.tables

SELECT T.name
 FROM [DB_TableInfo] D 
 join sys.tables T ON D.TableID = T.object_id
 WHERE D.Type = 'R' 

And to exclude empty tables

SELECT t.name
FROM DB_TableInfo d 
JOIN sys.tables t ON d.TableId = t.object_id
JOIN sys.dm_db_partition_stats ps ON ps.object_id = t.object_id
WHERE d.Type = 'R' and ps.index_id <= 1
GROUP BY d.TableId, t.name
HAVING SUM(ps.row_count) > 0
Martin Smith
check my edit in the post. I tried that query but it gave me an error
Reda
@Reda - Because you weren't using it right. Compare my query with your query!
Martin Smith
thx a lot Martin Smith it worked =)
Reda
@Martin: Is there a way to skip empty tables? because I found out that some root tables hold no values
Reda
@Reda - You could join onto `sys.dm_db_partition_stats` and exclude those with a rowcount of zero.
Martin Smith
@Martin: could you please help me out with this I need this query to carry on! thanks in advance
Reda
@Reda - See edit.
Martin Smith
thx a lot man I really appreciate it!
Reda