January 29, 2003 at 9:05 am
I'm new with SQL and i'm trying populate a table using sp_msforeachdb. Here is my code:
declare @DB_name varchar(25),
@Objectcount smallint
Exec sp_msforeachdb @command1= "use ?;select db_name() as
DB_name, count(*) as objectcount from sysobjects",
I'm trying to insert the data that was stored on DB_Name & objectcount to a table.
Any suggestions?
January 29, 2003 at 9:20 am
try this:
USE master
DECLARE @dbname CHAR(20), @name VARCHAR(12), @sql NVARCHAR(4000)
DECLARE dbs CURSOR FOR
SELECT name FROM sysdatabases
OPEN dbs
FETCH NEXT FROM dbs INTO @dbname
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT @name = LTRIM(RTRIM(@dbname))
SELECT @sql = N'
SELECT
''' + @name + ''' AS ''DB_NAME''
, COUNT(*) AS objectcount
FROM ' + @name + '.dbo.sysobjects'
EXEC sp_executesql @sql
PRINT ''
FETCH NEXT FROM dbs INTO @dbname
END
CLOSE dbs
DEALLOCATE dbs
GO
January 29, 2003 at 11:04 am
Thanks for your help. I was wondering what is the N for?
January 29, 2003 at 11:16 am
quote:
Thanks for your help. I was wondering what is the N for?
The "N" indicates that the string might contain unicode characters (in db names for instance), and so the executesql should treat the string as type NVARCHAR. This is more precautionary than anything. It just prevents some nasty, sometimes hard-to-diagnose bugs during execution...
January 29, 2003 at 2:25 pm
Just to show the sp_msforeachdb way as you tried initially.
Exec sp_msforeachdb @command1= 'select db_name() as
DB_name, count(*) as objectcount from ?..sysobjects'
Note don't worry with use in statement as you just need the 3 part name. Use ' instead of " which is standards not anything more. And I use [] around ? just to be sure of old things like DBs with numbers for names or white space in name but forum code gives issue here to see.
Also to do your insert then you just do.
Exec sp_msforeachdb @command1= 'INSERT dbname.objectower.tablename (col1, col2)select db_name() as
DB_name, count(*) as objectcount from ?..sysobjects'
Edited by - antares686 on 01/29/2003 2:27:01 PM
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply