Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Update all databases on a server

Status
Not open for further replies.

DanC

Programmer
Jan 12, 2001
65
US
I need to add a column to an existing table in almost every database on our server (80+ db's) Not every database has the table, only about 75% of them. Is there any way using the sysdatabases table in the master db to cycle through the databases checking for the existence of the table, and if it exists, adding the column?

Thanks in advance.
 
Use sp_MSforeachdb (a very, very useful undocumented SP!)

EXEC sp_MSforeachdb @command1 = 'if exists select * from sysobjects where name = "TABLE" and xtype = "U" alter table .......... '
 
still having a problem, the procedure seems to only be running in the currently select DB in query analyzer. This is essentially the query I'm trying to run:

EXEC sp_MSforeachdb @command1 = 'if exists (select * from dbo.sysobjects where id = object_id(N''[SYS_USER]'') and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
INSERT INTO [SYS_USER]([USER_ID], [PASSWORD], [PREFIX], [FIRSTNAME], [MIDNAME], [LASTNAME])
VALUES(''rbonhagen'', null, ''Mr.'', '''', null, ''Bonhagen'')'

 
Modify the query as follows. Use ?; will set the cuurent database context to the database being processed ny sp_msforeachdb.

EXEC sp_MSforeachdb @command1 =
'Use ? ; if exists (select * from dbo.sysobjects
where id = object_id(N''[SYS_USER]'')
and OBJECTPROPERTY(id, N''IsUserTable'') = 1)
INSERT INTO [SYS_USER]([USER_ID], [PASSWORD], [PREFIX],
[FIRSTNAME], [MIDNAME], [LASTNAME])
VALUES(''rbonhagen'', null, ''Mr.'',
'''', null, ''Bonhagen'')'
If you want to get the best answer for your question read faq183-874 and faq183-3179.
Terry L. Broadbent - DBA
SQL Server Page:
 
DOH!! thanks Terry

Dan, my apologies.. forgot to include that.
 
thanks for both of your help, it's much appreciated.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top