Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

I'm using this T-SQL to get index stats (edited for brevity):

SET @db_id = DB_ID(N'TestDB');
SET @object_id = OBJECT_ID(N'TestDB.dbo.Users');
SELECT * FROM sys.dm_db_index_physical_stats(@db_id, @object_id, NULL, NULL , 'LIMITED');

I want to be able to encapsulate this into a stored proc and call it for whichever database the stored proc is in, but the DB name is hard-coded, how can I get the database name dynamically?

Does T-SQL have anything like:

SET @db_id = DB_ID(this);

share|improve this question
2  
Have a look at db_name() –  dezso Feb 6 '13 at 8:48

1 Answer 1

up vote 6 down vote accepted

If db_id() is called with no parameter it returns the id of the current database - http://msdn.microsoft.com/en-us/library/ms186274.aspx

so you could just use: set @db_id=db_id()

And having read the rest of the question, you could call object_id() without the db name. If the object exists you'll get the id, if not NULL. So: SET @object_id = OBJECT_ID(N'dbo.Users');

share|improve this answer
    
Thanks, I'm thinking I'll pass the name into the sproc and have an option to run for all tables. –  SteB Feb 6 '13 at 10:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.