Get all database names from multiple servers - tsql

We have multiple SQL Servers and most of them are standalone. I am in need of creating a stored procedure / view that would insert all database names into a table from all servers.
Is there a way to do this via a stored procedure or a view? I do not have any powershell or .Net experience.
Here's what I have so far. I just can't figure out how to 'jump' from server to server and add all my results into a real table.
CREATE TABLE ##temp
(
DATABASE_NAME VARCHAR(100),
DATABASE_SIZE INT,
REMARKS VARCHAR(500)
)
INSERT into ##temp
EXEC [sp_databases]
--doing this to also get ServerName along with the db name.
--When I insert into a real table, I'll seperate it into two columns plus remove "#_!_#"
update ##temp
set DATABASE_NAME = (select ##SERVERNAME ) + '#_!_# ' + DATABASE_NAME
where DATABASE_NAME not like '%#_!_#%'
select DATABASE_NAME from ##temp

SQL Server Management Studio allows you to execute a query against multiple servers using the Registered Servers feature. This was added in SQL Server 2008 as this tutorial shows so you shouldn't worry about compatibility.
Running multi-server queries is easy:
From the View menu, select `Registered Servers. This will open a new window similar to the Object Explorer that displays the objects of a single server.
Add connections for all your servers connection details in the Local Server Groups folder
Right-click on the Local Server Groups folder and select New Query. The query you enter here will run an all registered servers.
To find all databases run select * from sys.databases or just sp_databases
SSMS will collect the results from all servers and display them in a grid. If you want the results to go to a single server's table though, you'll have to add the target server as a linked server to all others and use a four-part name to target the target table, eg INSERT INTO myManagementServer.MyDb.dbo.ThatTable...
SQL Server has even more powerful features for managing multiple servers. You can administer multiple servers through a Central Management Server and apply settings to multiple servers through policies. That feature was also added in 2008.
In SQL Server 2008 R2 the SQL Server Utility was added which goes even farther and collects diagnostics, metrics, performance data from multiple servers and stores it in a management warehouse for reporting. Imagine being able to see eg storage and query performance for multiple servers, or free space trends for the last X months.
The drawbacks are that historical data needs space. Collecting it also requires adding some stored procedures to all monitored servers, although this is done automatically.

For this kind of thing it's good to have at least one server that has a linked connection to all the servers you need information for. If you do then you can use this little script I just wrote:
-- (1) Create global temp table used to store results
IF OBJECT_ID('tempdb..##databases') IS NOT NULL DROP TABLE ##databases;
CREATE TABLE ##databases
(
serverDBID int identity,
serverName varchar(100),
databaseName varchar(100),
databaseSize decimal(20,6)
);
-- (2) Create and populate table variable used to collect server names
DECLARE #servers TABLE(id int identity, serverName varchar(100));
INSERT #servers(serverName)
SELECT name FROM sys.servers;
-- (3) loop through each DB and collect database names into ##databases
DECLARE #i int = 1, #serverName varchar(100), #db varchar(100), #sql varchar(8000);
WHILE #i <= (SELECT COUNT(*) FROM #servers)
BEGIN
SELECT #serverName = serverName FROM #servers WHERE id = #i;
SET #sql = 'INSERT ##databases(serverName, databaseName) SELECT '''+#serverName+
''', name FROM master.sys.databases';
EXEC (#sql);
SET #i += 1;
END;
-- (4) Collect database sizes
SET #i = 1; -- reset/re-use #i;
WHILE #i <= (SELECT COUNT(*) FROM ##databases)
BEGIN
SELECT #serverName = serverName, #db = databaseName
FROM ##databases
WHERE serverDBID = #i;
SET #sql =
'UPDATE ##databases
SET databaseSize =
(SELECT sum(size)/128. FROM ['+#serverName+'].['+#db+'].sys.database_files)
WHERE serverDBID = '+CAST(#i AS varchar(4))+';'
BEGIN TRY
EXEC (#sql);
END TRY
BEGIN CATCH
PRINT 'There was an error getting dbsize info for '+#serverName+' > '+#db;
END CATCH;
SET #i += 1;
END;
-- Final Output
SELECT * FROM ##databases;

Related

Can we create a trigger (or any object) to catch each login name

Actually I need to find all the users logged into a SQL Server in last month, so that I can delete the users which are not using SQL Server from AD group.
I was not able to find that so now I am trying to create trigger so that after one month I can delete users.
Under the server properties select the Security tab and enable Login auditing for "Both failed and successful logins". The information is then recorded in the SQL Server Logs.
It is also possible to do it via trigger. Something like
CREATE TRIGGER Logon_Audit
ON ALL SERVER
FOR LOGON
AS
BEGIN
declare #acct as nvarchar(max)
set #acct = ORIGINAL_LOGIN()
-- insert #acct into some table
END
I used fully qualified name for table and deleted multiple records
Create Table LoginDetails (iD int identity(1,1),LoginName nvarchar(max) , LoginTime datetime)
Create TRIGGER Logon_Audit
ON ALL SERVER
FOR LOGON
AS
BEGIN
declare #acct as nvarchar(max)
declare #LoginTime as nvarchar(max)
set #acct = ORIGINAL_LOGIN()
set #LoginTime = getdate()
insert into master..LoginDetails
Select top 1 #acct,#LoginTime
delete
from master..LoginDetails
where id not in (
Select max(id)
from LoginDetails
group by LoginName,LoginTime
)
END

Import Proc definition from network file with BULK

I'm trying to create 1000+ Procs in MS SQL from supplied physical files as part of legacy migration located on Network . For now I plan to use sp with dynamic SQL to loop over all of them like in segment below, I had problem with BULK ROWTERMINATOR, so I just dummied it with bunch of ZZZZ, is there any other correct way to set it to NONE, so all string will be loaded into single row for run. I also use Nvarchar(Max) for my field.
DROP TABLE IF EXISTS #imp;
CREATE TABLE #imp (Col varchar(max))
BULK INSERT #imp
FROM '//TFSNetwork/log/Install/sp_Test02.sql'
WITH (ROWTERMINATOR = '\nzzzzzzzzzZZZ') ---<< ?????
select top 1 #Sql = Col from #imp
EXEC (#sql);
----------------------------------------------------sp_Test02.sql
CREATE PROCEDURE [dbo].[sp_Test]
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET NOCOUNT ON;
SELECT GETDATE() AS TS
END
-----------------------------------------------------------------
Load whole file into single row/column
ROWTERMINATOR = '\n' is what used by default ,that's why you get it once omitted at all. Don't think we can or will want to change this behavior rather use your Z combo).
Same thing can be done with another BULK , in this case no need any ROWTERM options.
declare #myFile varchar(max)
select #myFile = BulkColumn
from openrowset(BULK '//Network/Path/Test02.sql', single_blob) x;
SELECT #myFile

Create a table or view from EXEC statement SQL Server

EXEC('Select
trim(field1) field1
CVDATE(date1) date1
from tabel1
where trim(field1) <> 'ABC' ') at AE --linked server
I need to dump the result generated from EXECUTION statement into a view. Is this possible? I am guessing the query is written this way is due to performance reasons
You can use the openquery to run the SELECT on remote server and create a view from the result set.
Here is a code sample. The sample creates local1 as the linked server and executes the query on it. If you already have your linked server registered, you don't need to run the step 1 and 4.
-- Step 1. register a linked server
exec sp_addlinkedserver
#server = 'local1',
#srvproduct = '',
#provider='SQLNCLI',
#datasrc = 'NameOfTheRemoteServer' -- if server has multiple instances use 'NameOfTheServer\NameOfTheInstance'
go
-- Step 2. run the query on remote server and create a view out of the results
create view ViewTest
as
select * from openquery(
local1,
'select
top 10
lower(AddressLine1) as Street,
ModifiedDate as dt
from AdventureWorks2014.Person.Address'
)
go
-- Step 3. check the view
select * from ViewTest
go
-- Step 4. finally drop the linked server
sp_dropserver 'local1'
go

How to convert SQL Server 2008 R2 database to SQL Server 2012?

I installed SQL Server 2012, and attached a database originally generated by SQL Server 2008 R2.
Everything appeared to work perfectly, with one problem: merges dropped from 1000 per second to 10 per second (a 100x slowdown).
I'm surmising that its because I am accessing a SQL Server 2008 R2 database from SQL Server 2012. Is there some way to convert the database to SQL Server 2012 format? Or is there something else thats going on that might explain the 100x slowdown in performance?
Please make sure that you set the compatibility mode of the database to 110, and update statistics.
ALTER DATABASE MyDatabase SET COMPATIBILITY_LEVEL = 110;
DECLARE #sql NVARCHAR(MAX) = N'';
SELECT #sql += CHAR(13) + CHAR(10) + 'UPDATE STATISTICS '
+ QUOTENAME(SCHEMA_NAME(schema_id))
+ '.' + QUOTENAME(name) + ' WITH FULLSCAN;'
FROM sys.tables;
PRINT #sql;
--EXEC sp_executesql #sql;
When I ran the SQL in the answer the nvarchar overflowed. The problem is when your database has too many tables the SQL is too long for an nvarchar. My database had enough tables to overflow a varchar (twice as long as a nvarchar). So I edited the SQL to loop through each table and execute separate statements. This way you wont miss updating the stats on any of your tables.
ALTER DATABASE MyDatabase SET COMPATIBILITY_LEVEL = 110;
DECLARE #SQL NVARCHAR(MAX) = N'';
Declare #Tables table
([Schema] nvarchar(50)
,[TableName] nvarchar(100))
Insert into #Tables
Select QUOTENAME(SCHEMA_NAME(schema_id)),QUOTENAME(name)
FROM sys.tables;
Declare #Schema nvarchar(50), #TableName nvarchar(100)
While Exists(Select * From #Tables)
Begin
Select Top 1 #Schema = [Schema], #TableName = [TableName] From #Tables
Set #SQL = 'UPDATE STATISTICS ' + #Schema + '.' + #TableName + ' WITH FULLSCAN;'
Begin Try
EXEC SP_ExecuteSql #SQLToExecute = #SQL
Print 'Completed: ' + #SQL
End Try
Begin Catch
DECLARE #ErrMsg nvarchar(4000)
SELECT #ErrMsg = SubString(ERROR_MESSAGE(),0,900)
Select GetDate(), 'Failed updating stats on ' + #Schema + ' ' + #TableName + '. Error: '+#ErrMsg
End Catch
Delete From #Tables Where [Schema] = #Schema and [TableName] = #TableName
End
Updating the Stats is must when you detach and attach database. Otherwise query planner cannot generate efficient execution plan and end-up with long execution time. This is what I noticed.
To upgrade a database file to use LocalDB:
1.In Server Explorer, choose the Connect to Database button.
2.In the Add Connection dialog box, specify the following information:
Data Source: Microsoft SQL Server (SqlClient)
Server Name: (LocalDB)\v11.0
Attach a database file: Path, where Path is the physical path of the primary .mdf file.
Logical Name: Name, where Name is the name that you want to use with the file.
Choose the OK button.
When prompted, choose the Yes button to upgrade the file.
Is this on the right track:
http://msdn.microsoft.com/en-us/library/ms189625.aspx
USE master;
GO
CREATE DATABASE MyDatabase
ON (FILENAME = 'C:\MySQLServer\MyDatabase.mdf'),
(FILENAME = 'C:\MySQLServer\Database.ldf')
FOR ATTACH;
GO

How to create DDL trigger to all databases in SQL Server 2005 instance

I am going to create a DDL trigger to all databases in SQL Server instance. I'd like to do it in one run instead of many runs for each database.
Below are the two T-SQL statements I need to execute:
-- Create table
use <dbname>
GO
CREATE TABLE dbo.ChangeAttempt
(EventData xml NOT NULL,
AttemptDate datetime NOT NULL DEFAULT GETDATE(),
DBUser char(50) NOT NULL)
GO
-- Create DDL trigger
use <dbname>
GO
CREATE TRIGGER db_trg_ObjectChanges
ON DATABASE
FOR ALTER_PROCEDURE, DROP_PROCEDURE,
ALTER_INDEX, DROP_INDEX,
ALTER_TABLE, DROP_TABLE, ALTER_TRIGGER, DROP_TRIGGER,
ALTER_VIEW, DROP_VIEW, ALTER_SCHEMA, DROP_SCHEMA,
ALTER_ROLE, DROP_ROLE, ALTER_USER, DROP_USER
AS
SET NOCOUNT ON
INSERT dbo.ChangeAttempt
(EventData, DBUser)
VALUES (EVENTDATA(), USER)
GO
My question is: how can I programmaticaly create DDL trigger in one run?
why do you need one run? this is the only way to do it.
Msg 111, Level 15, State 1, Line 2
'CREATE TRIGGER' must be the first statement in a query batch.
run the output generated by this:
DECLARE #DatabaseName varchar(500)
DECLARE #Database_id int
DECLARE #Query varchar(8000)
DECLARE #CRLF char(2)
SET #CRLF=CHAR(13)+CHAR(10)
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
select #Database_id=MIN(database_id) from sys.databases where database_id IN (5,7,8,6)
WHILE #Database_id IS NOT NULL
BEGIN
SELECT #DatabaseName=name from sys.databases where database_id=#Database_id
SET #Query='-- Create table'+#CRLF+#CRLF
+'use '+#DatabaseName+#CRLF
+' GO'+#CRLF
+' CREATE TABLE dbo.ChangeAttempt'+#CRLF
+' (EventData xml NOT NULL,'+#CRLF
+' AttemptDate datetime NOT NULL DEFAULT GETDATE(),'+#CRLF
+' DBUser char(50) NOT NULL)'+#CRLF
+'GO'+#CRLF+#CRLF
+'-- Create DDL trigger '+#CRLF+#CRLF
+'use '+#DatabaseName+#CRLF
+'GO'+#CRLF
+'CREATE TRIGGER db_trg_ObjectChanges'+#CRLF
+'ON DATABASE'+#CRLF
+'FOR ALTER_PROCEDURE, DROP_PROCEDURE,'+#CRLF
+' ALTER_INDEX, DROP_INDEX,'+#CRLF
+' ALTER_TABLE, DROP_TABLE, ALTER_TRIGGER, DROP_TRIGGER,'+#CRLF
+' ALTER_VIEW, DROP_VIEW, ALTER_SCHEMA, DROP_SCHEMA,'+#CRLF
+' ALTER_ROLE, DROP_ROLE, ALTER_USER, DROP_USER'+#CRLF
+'AS'+#CRLF
+'SET NOCOUNT ON'+#CRLF
+'INSERT dbo.ChangeAttempt'+#CRLF
+'(EventData, DBUser)'+#CRLF
+'VALUES (EVENTDATA(), USER)'+#CRLF
+'GO'+#CRLF
PRINT #Query
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
select #Database_id=MIN(database_id) from sys.databases WHERE database_id IN (5,7,8,6) AND database_id>#Database_id
END
EDIT
to determine what databases to generate scripts for do the following:
run this query:
select database_id,name from sys.databases
find all of the databases you want to run the scripts for
change my above script in two places (before loop & at bottom in loop) so all of the database_id that you want are in the following code section:
WHERE database_id IN (AAA,BBB,CCC,DDD,....)
You could use sp_MSforeachdb.
Something like this
sp_MSforeachdb
'
CREATE TABLE ?.dbo.ChangeAttempt
etc. etc. etc.
'
sp_MSforeachdb
'
CREATE TRIGGER ?.dbo.db_trg_ObjectChanges
etc. etc. etc.
'
I haven't tested this, in theory I'd expect it to work though. You want to make sure you exclude the system databases though.