I'm attempting to write a script that iterates over all tables and their columns in all databases resident to a SQL Server connection. I can do either of these but cannot figure out how to merge the two together. The problem is that at the time that the table/column information is collected, it comes out of the system tables of the current default database and I can't quite figure out how to change default databases in a way that is acceptable under the current conditions. I can't create and write to the many database new stored procedures to handle the changing of default database and I don't want to use undocumented functions.
but am having trouble prizing the information out of sysobjects, syscolumns and systypes on databases that are not currently the current database in use in order to find all occurrences of some string in all databases, no matter what table or column that string resides. One of the things making it harder is that I do not want to generate stored procedures on the fly and add them to the databases being probed so everything has to be accomplished either directly or by executing a sql string.
There are two obvious approaches to the problem -
1) Change the current database (Like 'use @DBNameVar' only something that actually works)
2) Directly access sysobjects, syscolumns and systypes in a different database
Here's what I have so far - I have figured out how to make a cursor that will list all of the databases and can load that database name into a string variable and I know how to get a listing of all of the tables and columns within a database. I have another piece of script that does a great job of probing all of the columns in all of the tables for a string.
Will the systables allow access if their database is not the current database? If so, what is the syntax? Can you show me what I need to do in my table/column iteration script? Assume, for example, that @DBNameVar contains the name of the database that needs to be probed. What is the syntax that will combine that database name with the following script which lists all of the tables/column?
DECLARE cCursor CURSOR LOCAL FAST_FORWARD FOR SELECT '[' + usr.name + '].[' + tbl.name + ']' AS tblName, '[' + col.name + ']' AS colName, LOWER(typ.name) AS typName FROM
-- How can a sysobjects from another database be specified???? sysobjects tbl INNER JOIN( syscolumns col INNER JOIN systypes typ ON typ.xtype = col.xtype ) ON col.id = tbl.id -- LEFT OUTER JOIN sysusers usr ON usr.uid = tbl.uid WHERE tbl.xtype = 'U' AND LOWER(typ.name) IN( 'char', 'nchar', 'varchar', 'nvarchar', 'text', 'ntext' ) ORDER BY tbl.name, col.colorder
Richard Lewis Haggard