Nice explanation logixologist.
Because Tom wants to run it for multiple select statements, i was thinking he could store all the table names in a column and use a cursor to fetch the table values. Considering you would create a table first such as:
CREATE TABLE tableName ( name varchar(20));
then run the following code once you inserted the right values in the table above.
Declare @table VARCHAR(255)
DECLARE @sql as varchar(max)
SET @SQL = 'SELECT * FROM' + 'dbo.' + @table + ' with (NOLOCK)'
DECLARE table_cursor CURSOR FOR
select distinct([name]) FROM DBname.dbo.tableName
Where [name] is not null
OPEN table_cursor
FETCH Next from table_cursor
INTO @table
WHILE @@FETCH_STATUS =0
BEGIN
EXEC @SQL
FETCH NEXT FROM table_cursor
INTO @table
END
CLOSE table_cursor
DEALLOCATE table_cursor
The cursor would return the table name for the select statement. I think you could use the same logic for insert statements.
DoQuery(@test)and encapsulate theEXECcallreplaceon those strings to fill in any values than to dynamically assemble the whole thing. It sounds like your concern is primarily with ease of development/ maintenance. If you have a stringselect * from ##dbname##.dbo.tablename with (nolock), you can doreplace(your_string, '##dbname##, 'Appt')and then execute that. If you are just replacing database names, maybe you just needsp_MSforeachDB.