2

TableA exists in all 4 DBs, run this,

Use DB1
go
select CurrentDB=DB_NAME(), * From DB1..TableA union all
select CurrentDB=DB_NAME(), * From DB2..TableA union all
select CurrentDB=DB_NAME(), * From DB3..TableA union all
select CurrentDB=DB_NAME(), * From DB4..TableA

always got CurrentDB ='DB1'. is there a Simple way to get DB2,3,4 when the rows are pulling from non-DB1? Trying to avoid hard code.

7
  • 1
    Is there some reason you didn't just do Select 'DB1, * From Db1.... Union all select 'DB2',... etc? Commented Mar 4, 2015 at 22:31
  • @Tony. I could, just thought someone might know a less 'hard-coded' version. Commented Mar 4, 2015 at 22:35
  • 2
    Less hard coded?? Hard coding is not a precentage, it is either is or it isn't. You already have to put in the database to pull from. Just type in the name and be done with it. There are other ways to do this but it doesn't provide much, if any, benefit. Commented Mar 4, 2015 at 22:38
  • Have a look at sp_msforeachdb, or you could do a cursor, but seeing as you've already hard-coded in the from clause I fail to see the point. Commented Mar 4, 2015 at 22:40
  • I think it's a reasonable idea to minimize the number of references to the database name if it were possible to do that. Unfortunately it's not. Commented Mar 4, 2015 at 23:08

2 Answers 2

1

Create the same view in each database that returns the value of DB_NAME() as a column. Then, in the union, the each row will include the database name.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

Use Master
set NOCOUNT ON;
Declare @db_name Varchar(12)
Declare @sql Varchar(1000)

Declare db_cursor CURSOR FOR 
  SELECT [name]
  FROM sys.databases Where [name] like 'DB[123456789]'

Open db_cursor

Fetch Next FROM db_cursor INTO @db_name
if @@FETCH_STATUS = 0
begin
  Select @sql = 'select ''' + @db_name + ''', * From ' + @db_name + '..TableA'
  Fetch Next FROM db_cursor INTO @db_name
  While @@FETCH_STATUS = 0
  begin
    select @sql = @sql + ' Union all select ''' + 
           @db_name + ''', * From ' +   @db_name + '..TableA'
    Fetch NEXT FROM db_cursor INTO @db_name
  end
  exec @sql
end
Close db_cursor
Deallocate db_cursor

Not tested, but basic idea is get all the matching db names. Build the sql statement, then exec it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.