0

I currently have many databases on a server. I want to run a query on only databases that end in "AccountsLive".

Not all of them end with this, so I kind of want to do a wildcard %AccountsLive query and not using a WHERE NOT name IN('master', 'tempdb', 'model', 'msdb')

Is this possible?

Below is the code I currently have:

DECLARE @Sql NVARCHAR(MAX) = NULL;

SELECT  @Sql = COALESCE(@Sql + ' UNION ALL ' + CHAR(13) + CHAR(10), '' ) + 'SELECT * FROM ' + QUOTENAME([name]) + '.SL_TRANSACTIONS'
FROM    sys.databases
WHERE   not [name] in ('master', 'tempdb', 'model', 'msdb');


EXECUTE ( @Sql );
2
  • 5
    Did you try WHERE [name] LIKE '%AccountsLive' ? Commented Mar 8, 2021 at 3:20
  • no i didn't try it as i am an idiot!! thank you!! Commented Mar 8, 2021 at 5:49

1 Answer 1

2

You can put list of table names in a table variable and query them accordingly. I have also added schema as dbo, to make the name as three part name, assuming the table in the dbo schema.

DECLARE @table table(dbname sysname)

INSERT INTO @table(dbname)
SELECT NAME FROm sys.databases where name like '%AccountsLive'

DECLARE @Sql NVARCHAR(MAX) = NULL;

SELECT  @Sql = COALESCE(@Sql + ' UNION ALL ' + CHAR(13) + CHAR(10), '' ) + 'SELECT * FROM ' + QUOTENAME(dbname) + '.dbo.SL_TRANSACTIONS'
FROM    @table


EXEC( @Sql );
Sign up to request clarification or add additional context in comments.

4 Comments

actually, i am getting an error on this one: Implicit conversion of varchar value to varchar cannot be performed because the collation of the value is unresolved due to a collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in UNION ALL operator. any ideas?
@PeterK, can you please raise separate question. It seems some issue with different collation in different databases. Please put query and add separate question. It is different error.
ah sorry, thought it may be linked to this - will do!
@PeterK, no problem. sure.

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.