last day (15 days later) » 

2:29 PM
1
A: adding DB name to a multiple database search - SQL

gotqnTry this: DROP TABLE IF EXISTS #DataSource; CREATE TABLE #DataSource ( [database] SYSNAME ,[user_id] BIGINT ); DECLARE @DynamicTSQLStatement NVARCHAR(MAX); SELECT @DynamicTSQLStatement = STRING_AGG(CAST('IF EXISTS(SELECT 1 FROM ' + QUOTENAME([name]) + '.[sys].[tables] WHERE [name] = ''s...

 
I'm getting an The server principal "****" is not able to access the database "****" under the current security context. error on this...any ideas?
 
@PeterK Ut seems you have not access to all databases. Can you run the query with sys.admin for example?
 
I am not an SA....I thought your answer would only look in if it exists and wouldn't have to worry about restricted databases. This is what mine currently does and works as it is - is there a way to do the same with yours?
 
@PeterK as we are quiring sys.database you can add as many filters in the WHERE clause as you need.
 
I've tried updating yours to have SELECT @DynamicTSQLStatement = STRING_AGG(CAST('IF EXISTS (SELECT * FROM sys.tables WHERE name = ''sys_user'') which doesn't come up with any errors, but doesn't produce any data in the search results?
 
2:29 PM
@PeterK In the where clause just add few databases to test.
@PeterK check the second query
 
Thank you for helping...I've tried the second query and no errors but still now results, just the column names. I've tried adding one database in but still getting the same issue
 
What do you mean there is no results?
that the last select returns nothing?
 
2:41 PM
yes, it returns nothing....just the two column headings with no results in it
under messages it says "0 rows affected"
 
2:59 PM
ok then add WHERE clause
to filter the data for a particular database where the table exists
for example
DROP TABLE IF EXISTS #DataSource;

CREATE TABLE #DataSource
(
[database] SYSNAME
,[user_id] BIGINT
);

DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

SELECT @DynamicTSQLStatement = STRING_AGG(CAST('IF EXISTS(SELECT 1 FROM ' + QUOTENAME([name]) + '.[sys].[tables] WHERE [name] = ''sys_user'') INSERT INTO #DataSource ([database], [user_id]) SELECT DB_NAME(), user_id FROM ' + QUOTENAME([name]) + '.[dbo].[sys_user]' AS NVARCHAR(MAX)), ';')
FROM sys.databases
WHERE [name] = 'my database '

SELECT @DynamicTSQLStatement;
replace 'my database' with your database
and execute the query in order to return what is going to be execute
ok?
 
Still the same issue...I chose a database that I 100% know there is data for. I've taken out the database column to see if that in somewhere affects it, but just returns the user_id with no results
I've done a simple select user_id from db.dbo.sys_user where db is the database name and works as expected
 

last day (15 days later) »