June 28, 2010 at 12:38 am
Hi All
I was trying to get the max length of table name in each database and used this query:
exec master..sp_msforeachdb 'select max(len(name)) from sys.tables'
but it returns max length from one databse only ,although records are repeated for each database.
Am I missing something here??
Online Trainer For SQL DBA and Developer @RedBushTechnologies with 18 yrs exp.
June 28, 2010 at 1:44 am
sp_msforeachdb uses the ? placeholder for the current database being processed.
This should do the trick.
exec master..sp_msforeachdb 'select max(len(name)) from [?].sys.tables'
-- Gianluca Sartori
June 28, 2010 at 5:15 am
Thanks for the reply..it makes me wonder why at times we dont have to supply a placeholder and it still works
Online Trainer For SQL DBA and Developer @RedBushTechnologies with 18 yrs exp.
June 28, 2010 at 5:41 am
suresh kumar Sulakh (6/28/2010)
Thanks for the reply..it makes me wonder why at times we dont have to supply a placeholder and it still works
that's because the command is repeating over and over in the same database you are currently connected in; the sp_msForEachDb is just the cursor that runs it for each database.
compare the results of these two:
exec master..sp_msforeachdb 'select ''?'' as dbName, db_name() as CurrDB,max(len(name)) as mxLen from ?.sys.tables'
exec master..sp_msforeachdb 'select ''?'' as dbName, db_name() as CurrDB,max(len(name)) as mxLen from sys.tables'
the second one, which is not using the ? placeholder, is just getting the same length over and over again, where the first one is getting it for each db because of the placeholder changing the db context.
Lowell
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply