2

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);

6

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');

  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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