My own raspberry pi cloud

When I was first working with computers, I used to build and upgrade my own desktop PCs.  This was back when finished PCs were pricey and it was cheaper to build your own if you were willing to put in the time and effort.  There were times of frustration but ultimately a sense of accomplishment when you were finished.  A lot of knowledge of the inner workings of a PC as well as tuning tips and tricks were earned as well.

Many years later, hardware is still relatively cheap, but a finished PC is as well.  Laptops have also replaced desktops in many situations now that their pricing has become more affordable.  Now it is typically game players and hobbyists whom still actually build desktops.

I gave up building my own desktops long ago, but I still have one old Gateway PC for playing old FPS games like Doom when I’m feeling nostalgic.  When it finally conks out, I will probably have to set up a virtual machine or two for this task.

I started playing with virtual machines back when I wanted to work with versions of Oracle when they were first introduced.  As any Oracle veteran knows, the AIX, Unix, and Linux versions would always be rolled out first and it would be much later when the Windows versions were introduced.  Not wanting to wait for the Windows versions, I started using VMWare and eventually VirtualBox to start working with the Unix versions.

Over the years, I have massed quite a lot of VMs, not wanting to create them over and over to work with specific Oracle products and operating systems.  Colleagues have asked me for copies of some of these VMs from time to time and the size of them makes it difficult to post or send them.  This is also true for files, scripts, and toolkits that we as consultants carry around with us between client engagements.

The introduction of the Raspberry Pi has opened a new world of low-cost computing power that can be used in a variety of ways and I see new projects posted all the time – everything from weather stations to smart home devices.

I recently saw a project for a home cloud using a raspberry pi device that can be configured to upload and download files remotely and saw this as a way to post my VMs for my colleagues that were interested.  Since I have an old (version 2) raspberry pi laying around that I unsuccessfully tried to turn into a NAS, I thought it would be perfect for this use.

The process to create my own cloud was found here – https://pimylifeup.com/raspberry-pi-owncloud/ and the process allowed me to get my own cloud set up.

A word of caution, though.  Since this is not a highly-secured platform, do not place any sensitive files on this cloud.  If it is on your home network, it will require a port forward setting on your router to enable outside access.  On the positive side, you can have links secured with passwords for both folders and individual files to share with others.

 

Advertisements

MySQL 8 test environment setup

Having just passed the newly-revised MySQL 2019 Implementation Specialist certification (https://www.youracclaim.com/badges/0f7ee5bd-3f91-4611-8b33-08861f67bb7d/linked_in), I thought I would pass on some of the MySQL information in the form of an introduction for those thinking about creating an environment for experimentation.

My test environment will be created on an Oracle Enterprise Linux (OEL) version 7 update 7 virtual machine running under Oracle VirtualBox version 6.0.10 because I like doing things as cheaply as possible.

There are numerous articles on creating OEL virtual machines, so let me just say that OEL is available freely through Oracle E-delivery after creating a free account and Oracle VirtualBox is free as well and runs quite well under Windows 10.  For the Mac users out there, you will have to find your own virtual machine hosting utility.  Sorry, Mac.

My OEL7 VM is a simple construct of 2 CPU cores, 5GB of memory, and a 100GB dynamically sized HDD.  You should not need that much space, but I tend to size mine large and let them grow if needed.

Once the OEL7 VM is created and running, it needs to be able to access the internet to download the MySQL repository package as well as the actual MySQL software during the installation process.  Also, if you are not installing the software as the root user, the account you will be using will need sudo privileges.

Inside the VM, go to https://dev.mysql.com/downloads/repo/yum/ and download the desired repository RPM package.  An Oracle web account will be needed prior to being able to download.  You can use the one you created for the E-delivery download earlier if necessary.  Install the package with the command: sudo rpm -Uvh <package_name>.

Execute the following command to check the available MySQL versions from the newly-installed repository:

[jonadams@localhost Downloads]$ sudo yum repolist all | grep mysql

mysql-cluster-7.5-community/x86_64 MySQL Cluster 7.5 Community disabled
mysql-cluster-7.5-community-source MySQL Cluster 7.5 Community - disabled
mysql-cluster-7.6-community/x86_64 MySQL Cluster 7.6 Community disabled
mysql-cluster-7.6-community-source MySQL Cluster 7.6 Community - disabled
mysql-cluster-8.0-community/x86_64 MySQL Cluster 8.0 Community disabled
mysql-cluster-8.0-community-source MySQL Cluster 8.0 Community - disabled
mysql-connectors-community/x86_64 MySQL Connectors Community enabled: 118
mysql-connectors-community-source MySQL Connectors Community - disabled
mysql-tools-community/x86_64 MySQL Tools Community enabled: 95
mysql-tools-community-source MySQL Tools Community - Sourc disabled
mysql-tools-preview/x86_64 MySQL Tools Preview disabled
mysql-tools-preview-source MySQL Tools Preview - Source disabled
mysql55-community/x86_64 MySQL 5.5 Community Server disabled
mysql55-community-source MySQL 5.5 Community Server - disabled
mysql56-community/x86_64 MySQL 5.6 Community Server disabled
mysql56-community-source MySQL 5.6 Community Server - disabled
mysql57-community/x86_64 MySQL 5.7 Community Server disabled
mysql57-community-source MySQL 5.7 Community Server - disabled
mysql80-community/x86_64 MySQL 8.0 Community Server enabled: 129
mysql80-community-source MySQL 8.0 Community Server - disabled

You can see which versions and tools are enabled. The enabled ones will typically be
the newest versions.  Install the enabled community server:

[jonadams@localhost Downloads]$ sudo yum install mysql-community-server -y
Loaded plugins: langpacks, ulninfo
mysql-connectors-community | 2.5 kB 00:00:00
mysql-tools-community | 2.5 kB 00:00:00
mysql80-community | 2.5 kB 00:00:00
ol7_UEKR5 | 2.5 kB 00:00:00
ol7_latest | 2.7 kB 00:00:00
(1/4): ol7_UEKR5/x86_64/updateinfo | 50 kB 00:00:00
(2/4): ol7_latest/x86_64/updateinfo | 1.1 MB 00:00:01
(3/4): ol7_UEKR5/x86_64/primary_db | 6.6 MB 00:00:01
(4/4): ol7_latest/x86_64/primary_db | 20 MB 00:00:02
Resolving Dependencies
--> Running transaction check
---> Package mysql-community-server.x86_64 0:8.0.17-1.el7 will be installed
--> Processing Dependency: mysql-community-common(x86-64) = 8.0.17-1.el7 for package: mysql-community-server-8.0.17-1.el7.x86_64
--> Processing Dependency: mysql-community-client(x86-64) >= 8.0.11 for package: mysql-community-server-8.0.17-1.el7.x86_64
--> Running transaction check
---> Package mysql-community-client.x86_64 0:8.0.17-1.el7 will be installed
--> Processing Dependency: mysql-community-libs(x86-64) >= 8.0.11 for package: mysql-community-client-8.0.17-1.el7.x86_64
---> Package mysql-community-common.x86_64 0:8.0.17-1.el7 will be installed
--> Running transaction check
---> Package mariadb-libs.x86_64 1:5.5.64-1.el7 will be obsoleted
--> Processing Dependency: libmysqlclient.so.18()(64bit) for package: 2:postfix-2.10.1-7.el7.x86_64
--> Processing Dependency: libmysqlclient.so.18(libmysqlclient_18)(64bit) for package: 2:postfix-2.10.1-7.el7.x86_64
---> Package mysql-community-libs.x86_64 0:8.0.17-1.el7 will be obsoleting
--> Running transaction check
---> Package mysql-community-libs-compat.x86_64 0:8.0.17-1.el7 will be obsoleting
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================
Package Arch Version Repository Size
=============================================================================================================================
Installing:
mysql-community-libs x86_64 8.0.17-1.el7 mysql80-community 3.0 M
replacing mariadb-libs.x86_64 1:5.5.64-1.el7
mysql-community-libs-compat x86_64 8.0.17-1.el7 mysql80-community 2.1 M
replacing mariadb-libs.x86_64 1:5.5.64-1.el7
mysql-community-server x86_64 8.0.17-1.el7 mysql80-community 415 M
Installing for dependencies:
mysql-community-client x86_64 8.0.17-1.el7 mysql80-community 32 M
mysql-community-common x86_64 8.0.17-1.el7 mysql80-community 589 k

Transaction Summary
=============================================================================================================================
Install 3 Packages (+2 Dependent packages)

Total size: 453 M
Total download size: 415 M
Downloading packages:
No Presto metadata available for mysql80-community
warning: /var/cache/yum/x86_64/7Server/mysql80-community/packages/mysql-community-server-8.0.17-1.el7.x86_64.rpm: Header V3 DSA/SHA1 Signature, key ID 5072e1f5: NOKEY
Public key for mysql-community-server-8.0.17-1.el7.x86_64.rpm is not installed
mysql-community-server-8.0.17-1.el7.x86_64.rpm | 415 MB 00:01:24
Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
Importing GPG key 0x5072E1F5:
Userid : "MySQL Release Engineering <mysql-build@oss.oracle.com>"
Fingerprint: a4a9 4068 76fc bd3c 4567 70c8 8c71 8d3b 5072 e1f5
Package : mysql80-community-release-el7-3.noarch (installed)
From : /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
Installing : mysql-community-common-8.0.17-1.el7.x86_64 1/6
Installing : mysql-community-libs-8.0.17-1.el7.x86_64 2/6
Installing : mysql-community-client-8.0.17-1.el7.x86_64 3/6
Installing : mysql-community-server-8.0.17-1.el7.x86_64 4/6
Installing : mysql-community-libs-compat-8.0.17-1.el7.x86_64 5/6
Erasing : 1:mariadb-libs-5.5.64-1.el7.x86_64 6/6
Verifying : mysql-community-libs-8.0.17-1.el7.x86_64 1/6
Verifying : mysql-community-server-8.0.17-1.el7.x86_64 2/6
Verifying : mysql-community-common-8.0.17-1.el7.x86_64 3/6
Verifying : mysql-community-client-8.0.17-1.el7.x86_64 4/6
Verifying : mysql-community-libs-compat-8.0.17-1.el7.x86_64 5/6
Verifying : 1:mariadb-libs-5.5.64-1.el7.x86_64 6/6

Installed:
mysql-community-libs.x86_64 0:8.0.17-1.el7 mysql-community-libs-compat.x86_64 0:8.0.17-1.el7
mysql-community-server.x86_64 0:8.0.17-1.el7

Dependency Installed:
mysql-community-client.x86_64 0:8.0.17-1.el7 mysql-community-common.x86_64 0:8.0.17-1.el7

Replaced:
mariadb-libs.x86_64 1:5.5.64-1.el7

Complete!

Check the status of the mysqld service:

Start the mysqld service and check the status:

 

[jonadams@localhost Downloads]$ sudo systemctl start mysqld.service

[jonadams@localhost Downloads]$ sudo systemctl status mysqld.service
● mysqld.service – MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: active (running) since Mon 2019-09-16 13:42:19 MDT; 5min ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 5098 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 5183 (mysqld)
Status: “Server is operational”
Tasks: 39
CGroup: /system.slice/mysqld.service
└─5183 /usr/sbin/mysqld

Sep 16 13:42:13 localhost.localdomain systemd[1]: Starting MySQL Server...
Sep 16 13:42:19 localhost.localdomain systemd[1]: Started MySQL Server.

Get the temporary root password created during the first startup of the MySQL server:

[jonadams@localhost Downloads]$ sudo grep 'temporary password' /var/log/mysqld.log
2019-09-16T19:42:15.986474Z 5 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: 3dh>C0N!<Tpg

Change the root password as soon as possible by logging in with the generated,
temporary password and set a custom password for the superuser account:

shell> mysql -uroot -p

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'SemperFidelis1!';
Query OK, 0 rows affected (0.01 sec)

Note – MySQL’s validate_password plugin is installed by default. This will require that passwords contain at least one upper case letter, one lower case letter, one digit, and one special character, and that the total password length is at least 8 characters.

[jonadams@localhost Downloads]$ mysql -uroot -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.17

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

mysql> quit
Bye

Stop the mysqld service and check the status

[jonadams@localhost tmp]$ sudo systemctl stop mysqld.service
[jonadams@localhost tmp]$ sudo systemctl status mysqld.service
● mysqld.service - MySQL Server
Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
Active: inactive (dead) since Mon 2019-09-16 17:45:44 MDT; 7s ago
Docs: man:mysqld(8)
http://dev.mysql.com/doc/refman/en/using-systemd.html
Process: 5183 ExecStart=/usr/sbin/mysqld $MYSQLD_OPTS (code=exited, status=0/SUCCESS)
Process: 5098 ExecStartPre=/usr/bin/mysqld_pre_systemd (code=exited, status=0/SUCCESS)
Main PID: 5183 (code=exited, status=0/SUCCESS)
Status: "Server shutdown complete"

Sep 16 13:42:13 localhost.localdomain systemd[1]: Starting MySQL Server...
Sep 16 13:42:19 localhost.localdomain systemd[1]: Started MySQL Server.
Sep 16 17:45:42 localhost.localdomain systemd[1]: Stopping MySQL Server...
Sep 16 17:45:44 localhost.localdomain systemd[1]: Stopped MySQL Server.

Note that the entries are timestamped so at first glance it appears that the
service was started before it was shut down, but according to the timestamps,
it was stopped about 4 hours after it was started.

We now want to install the MySQL shell utility.  It allows you to execute commands in JavaScript, Python, or SQL without special considerations.

[jonadams@localhost lib]$ sudo yum install mysql-shell
Loaded plugins: langpacks, ulninfo
epel/x86_64/metalink | 11 kB 00:00:00
epel | 5.4 kB 00:00:00
mysql-connectors-community | 2.5 kB 00:00:00
mysql-tools-community | 2.5 kB 00:00:00
mysql80-community | 2.5 kB 00:00:00
ol7_UEKR5 | 2.5 kB 00:00:00
ol7_latest | 2.7 kB 00:00:00
(1/2): epel/x86_64/updateinfo | 1.0 MB 00:00:00
(2/2): epel/x86_64/primary_db | 6.8 MB 00:00:00
Resolving Dependencies
--> Running transaction check
---> Package mysql-shell.x86_64 0:8.0.17-1.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=============================================================================================================================
Package Arch Version Repository Size
=============================================================================================================================
Installing:
mysql-shell x86_64 8.0.17-1.el7 mysql-tools-community 15 M

Transaction Summary
=============================================================================================================================
Install 1 Package

Total download size: 15 M
Installed size: 50 M
Is this ok [y/d/N]: y
Downloading packages:
mysql-shell-8.0.17-1.el7.x86_64.rpm | 15 MB 00:00:02
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Installing : mysql-shell-8.0.17-1.el7.x86_64 1/1
Verifying : mysql-shell-8.0.17-1.el7.x86_64 1/1

Installed:
mysql-shell.x86_64 0:8.0.17-1.el7

Complete!

Verify the MySQL shell installation:

[jonadams@localhost lib]$ mysqlsh
MySQL Shell 8.0.17

Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates.
Other names may be trademarks of their respective owners.

Type '\help' or '\?' for help; '\quit' to exit.
MySQL JS >

The default shell interface for the MySQL shell utility is JavaScript.  To switch between the different interfaces, use these commands.  The prompt will change to reflect the current interface.

\js for JavaScript

\sql for SQL

\py for Python

MySQL Shell comes with the option of automatically saving the history of commands, but it is disabled by default. It is a handy feature, so use this process to activate it.

Show settings and look for history.autoSave

MySQL JS > shell.options

MySQL JS > \option --persist history.autoSave=1

You can close and reopen the session and in the new one press the arrow up key to verify that the commands from previous sessions are available.

Switch to SQL mode and connect to the MySQL instance:

MySQL … JS > \sql

MySQL SQL > \c root@localhost
Creating a session to 'root@localhost'
Please provide the password for 'root@localhost': ***************
Save password for 'root@localhost'? [Y]es/[N]o/Ne[v]er (default No): Y
Fetching schema names for autocompletion... Press ^C to stop.
Your MySQL connection id is 8 (X protocol)
Server version: 8.0.17 MySQL Community Server - GPL
No default schema selected; type \use <schema> to set one.

Notice that I opted for MySQL shell to save my user account password.  Next time I login, I will not have to type in the password after the connect command.

Now you can submit the usual SQL commands

SQL > show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.0006 sec)

Exit from MySQL Shell with “\q” or “\exit”

MySQL … JS > \q

Now that your test environment is set up, I recommend shutting it down and backing it up with the VirtualBox export tool in case your experimentation goes wrong.  It would also be a good time to review the MySQL 8 online documentation.  I recommend concentrating first on backup and recovery commands.

https://dev.mysql.com/doc/

Enjoy!

 

Creating SQL Server index fragmentation

In a few client environments, I have seen index monitoring and maintenance procedures triggered by fragmentation levels.  I have sometimes wondered how these procedures were tested when they were put in place, other than waiting for fragmentation to occur through normal operations.  Wouldn’t it be a good idea to have a process that generates a level of fragmentation to test these processes?

Here is a process that can be used as the basis for generating index fragmentation to properly test index monitoring and maintenance procedures.  I will create a test table, populate it with data, create an index on the test table, then execute a process that keeps inserting data into the test table until the desired level of index fragmentation is reached.

During testing, 100 rows were inserted into the test table initially, then each iteration of the fragmentation process inserted another 100 rows.  It took only two iterations through the process to produce 50 percent index fragmentation.  For more precise fragmentation, use a larger number of rows during the initial data insert.

NOTE – This process was created and tested on SQL Server 2016.  Be sure to set the database environment where you want to create the test table before executing these commands.

--Drop the test table if it exists
drop TABLE dbo.TestTable
GO

--Create the test table
CREATE TABLE dbo.TestTable
(
        RowID int IDENTITY(1,1),
	MyKeyField VARCHAR(10) NOT NULL,
	MyDate DATETIME NOT NULL,
	MyInt DATETIME NOT NULL,
	MyString VARCHAR(30) NOT NULL
)
GO

--Code to insert first rows into table 
DECLARE @RowCount INT
DECLARE @RowString VARCHAR(10)
DECLARE @Random INT
DECLARE @Upper INT
DECLARE @Lower INT
DECLARE @InsertDate DATETIME
DECLARE @s CHAR(30)

SET @Lower = -730
SET @Upper = -1
SET @RowCount = 0

WHILE @RowCount < 100  --Set this value to the number of rows desired
BEGIN
	SET @RowString = CAST(@RowCount AS VARCHAR(10))
	SELECT @Random = ROUND(((@Upper - @Lower -1) * RAND() + @Lower), 0)
	SET @InsertDate = DATEADD(dd, @Random, GETDATE())

SET @s = (
SELECT
	c1 AS [text()]
FROM
	(
	SELECT TOP (30) c1  --Change this value to the desired length of the resulting string.
	FROM
	  (
    VALUES
      ('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H'), ('I'), ('J'),
      ('K'), ('L'), ('M'), ('N'), ('O'), ('P'), ('Q'), ('R'), ('S'), ('T'),
      ('U'), ('V'), ('W'), ('X'), ('Y'), ('Z'), ('0'), ('1'), ('2'), ('3'),
      ('4'), ('5'), ('6'), ('7'), ('8'), ('9'), ('!'), ('@'), ('#'), ('$'),
      ('%'), ('&'), ('*'), ('('), (')'), ('?'), ('+'), ('-'), (','), ('.')
        ) AS T1(c1)
	ORDER BY ABS(CHECKSUM(NEWID()))
	) AS T2
FOR XML PATH('')
);

	INSERT INTO TestTable
		(MyKeyField
		,MyDate
		,MyInt
		,MyString)
	VALUES
		(REPLICATE('0', 10 - DATALENGTH(@RowString)) + @RowString
		, @InsertDate
		,RAND(@RowCount)
		,@s)

	SET @RowCount = @RowCount + 1
END
GO


--Verify number of row inserted into test table
select count(*)
from TestTable;


--Create index on test table
SET ANSI_PADDING ON
GO

CREATE NONCLUSTERED INDEX [dbo.TestTableIndex] ON [dbo].[TestTable]
(
	[MyString] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
GO

--Check initial fragmentation
select avg_fragmentation_in_percent
    from sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'LIMITED')
    where object_id = (select object_id from sys.tables where name = 'TestTable')
    AND index_type_desc = 'NONCLUSTERED INDEX'
GO


--Routine to loop through row inserts until fragmentation reaches desired level
DECLARE @FragEnd INT
DECLARE @FragPercent INT

SET @FragEnd = 30      --Set this number to degree of fragmentation desired 
SET @FragPercent = 0  
SET IDENTITY_INSERT [dbo].[TestTable] ON

WHILE @FragEnd > @FragPercent
BEGIN

  select @FragPercent = max(avg_fragmentation_in_percent)
  from sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, 'LIMITED')
  where object_id = (select object_id from sys.tables where name = 'TestTable')
  AND ALLOC_unit_type_desc = 'IN_ROW_DATA';

  insert into [dbo].[TestTable] ( [RowID],[MyKeyField],[MyDate],[MyInt],[MyString])
  select top(100) [RowID],[MyKeyField],[MyDate],[MyInt],[MyString]
  from dbo.TestTable;

END;
GO

 

SQL Server Migration Tool

I was recently asked to review a migration plan from SQL Server to Oracle. The actual export and import of the table data was broken into two separate tasks and the time projected was (in my opinion) overly long. I did not know the exact details of what steps were being performed during the export and import, but I immediately thought about improving the process by using the SQL Server Import and Export Wizard.

I first encountered the SQL Server Import and Export Wizard utility in the early days of working with SQL Server versions 7 and 2000 and before you ask, yes I am old.  I attended the Microsoft launch event for SQL Server 7 while living in Denver and even got the t-shirt!

Anyway, I was impressed with this tool even this early in its history and the fact that such a capable tool was bundled with SQL Server at no additional charge.  This is a practice that continues today.

The use of this tool is well-documented (https://docs.microsoft.com/en-us/sql/integration-services/import-export-data/import-and-export-data-with-the-sql-server-import-and-export-wizard?view=sql-server-2017), but I will give a brief overview in this post.

The SQL Server Import and Export Wizard can be accessed in a couple of ways.  The first is directly though the Start menu in Windows:

sql server mig tool 1

It is interesting to note that both 32 and 64-bit versions are available in this manner.  Another method of access is directly from the SQL Server Management Studio when right-clicking on a database, going to the tasks sub-menu, and selecting either import data or export data.

Once selected by either of these methods, the interface is the same:

sql server mig tool 2

Going to the next screen, you are prompted for a data source for your process.  The data sources range from .NET, to Access (remember it?), to ODBC data sources for Oracle and SQL Server.

sql server mig tool 3

Take note that Microsoft has a built-in OLE DB provider client for Oracle databases.  However, I have always found it easier to use the provider supplied by Oracle.  It would be necessary to install the Oracle client software on the Windows host to make this option available.  If using Oracle as a source or target for an import or export process, I tend to go through the Windows control panel and set up my connections before using the SQL Server Import and Export Wizard.  I found it easier, especially being familiar with Oracle networking.

The target options for the SQL Server Import and Export Wizard are similar to the source options.From here you get the idea that you can perform the import and export in one process, provided you get the target specifics taken care of first.

I recommend using this tool for your smaller data migration needs, even if you are not using SQL Server.  The drawback is that you will need access to SQL Server software to install this utility.

 

SQL Server Assessment Script

I finally get to cross an item off my back burner project list.  Last February, I was at a client assessing their entire SQL Server database footprint for migration to the cloud.  Not having done this kind of work before, I quickly cobbled together scripts that gave me a basic overview of each database.  I then combined the results into a spreadsheet.

Wouldn’t it have been nice to get this information in a single script?  You could use this script to not only get a better understanding of resource usage in your SQL Server instance, but also use it to determine needed resources for migrating to either other hardware or the cloud.

I have already produced a lengthy health check script (here) that gives quite a bit of information.  It did not, however, take measurements of CPU usage and IOPS values over a period of time.  My new SQL Server assessment script not only gathers a smaller but more critical set of information than my health check script, but also takes hourly snapshots of CPU usage and IOPS values including individual read and write values over the course of one day.  Execute this script during a normal working day or during a period of end-of-month processing, if it exists.

Here is the script in its latest form.  To adjust the CPU and IOPS snapshots taken and the interval between snapshots, edit these two lines:

while (@cntr) < 24 – This is the number of snapshots to take before results are produced.

waitfor delay ’01:00:00′  –  This is the time delay between snapshots.  It is currently set to one hour.

--sql_server_assessment.sql
 --Lists the resources and their usage for a single SQL Server instance
 --Intended to act as a tool for migrations to other hardware or the cloud.

use master
 GO
 ----------------------------------------------------------Node name

SELECT SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [CurrentNodeName];
 ----------------------------------------------------------Product Version, level, and Edition

SELECT
 CASE
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '8%' THEN 'SQL2000'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '9%' THEN 'SQL2005'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.0%' THEN 'SQL2008'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.5%' THEN 'SQL2008 R2'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '11%' THEN 'SQL2012'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '12%' THEN 'SQL2014'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '13%' THEN 'SQL2016'
 WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '14%' THEN 'SQL2017'
 ELSE 'unknown'
 END AS MajorVersion,
 SERVERPROPERTY('ProductLevel') AS ProductLevel,
 SERVERPROPERTY('Edition') AS Edition,
 SERVERPROPERTY('ProductVersion') AS ProductVersion

----------------------------------------------------------License information

print N'License information';

SELECT SERVERPROPERTY('LicenseType') AS LICENSE_TYPE,
 ISNULL(SERVERPROPERTY('NumLicenses'),0) AS NUM_LICENCES;
 ----------------------------------------------------------Database listing

print N'Database list with Status and Recovery Model';
 ----------------------------------------------------------Logical CPUs
 select cpu_count as logical_cpu_count
 from sys.dm_os_sys_info;
 ----------------------------------------------------------Physical Memory

--For SQL Server version 2008, 2008R2
 select physical_memory_in_bytes/1024/1024/1024 as GB
 from sys.dm_os_sys_info;

--For SQL Server version > 2008
 select physical_memory_kb/1024/1024 as GB
 from sys.dm_os_sys_info;

----------------------------------------------------------Memory usage per database

print N'Memory Usage per User Database';
 SELECT
 substring(DB_NAME(database_id),1,40) AS [Database Name]
 ,COUNT(*) * 8/1024.0 AS [Cached Size (MB)]
 FROM
 sys.dm_os_buffer_descriptors
 WHERE
 database_id > 4
 AND database_id <> 32767
 AND db_name(database_id) <> 'SSISDB'
 GROUP BY DB_NAME(database_id)
 ORDER BY [Cached Size (MB)] DESC OPTION (RECOMPILE);

----------------------------------------------------------Database file size and growth settings

print N'Size and Growth';
 select substring(b.name,1,40) AS DB_Name, substring(a.name,1,40) AS Logical_name,
 substring(a.filename,1,100) AS File_Name,
 cast((a.size * 8.00) / 1024 as numeric(12,2)) as DB_Size_in_MB,
 case when a.growth > 100 then 'In MB' else 'In Percentage' end File_Growth,
 cast(case when a.growth > 100 then (a.growth * 8.00) / 1024
 else (((a.size * a.growth) / 100) * 8.00) / 1024
 end as numeric(12,2)) File_Growth_Size_in_MB,
 case when ( maxsize = -1 or maxsize=268435456 ) then 'AutoGrowth Not Restricted' else 'AutoGrowth Restricted' end AutoGrowth_Status
 from sysaltfiles a
 join sysdatabases b on a.dbid = b.dbid
 where DATABASEPROPERTYEX(b.name, 'status') = 'ONLINE'
 order by b.name;

----------------------------------------------------------Database data and log file total size
 SELECT
 SUM(CASE WHEN type = 0 THEN MF.size * 8 / 1024.0 /1024.0 ELSE 0 END) +
 SUM(CASE WHEN type = 1 THEN MF.size * 8 / 1024.0 /1024.0 ELSE 0 END) AS Total_GB
 FROM
 sys.master_files MF
 JOIN sys.databases DB ON DB.database_id = MF.database_id
 WHERE DB.source_database_id is null;
 ----------------------------------------------------------License feature usage

IF OBJECT_ID('tempdb.dbo.##enterprise_features') IS NOT NULL
 DROP TABLE ##enterprise_features

CREATE TABLE ##enterprise_features
 (
 dbname SYSNAME,
 feature_name VARCHAR(100),
 feature_id INT
 )

EXEC sp_msforeachdb
 N' USE [?]
 IF (SELECT COUNT(*) FROM sys.dm_db_persisted_sku_features) >0
 BEGIN
 INSERT INTO ##enterprise_features
 SELECT dbname=DB_NAME(),feature_name,feature_id
 FROM sys.dm_db_persisted_sku_features
 END '
 SELECT *
 FROM ##enterprise_features;

----------------------------------------------------------CPU and IOPS for 24 hours (avg. work day or end of month)

create table #CPU (snap_time varchar(30),
 row_num int,
 db_name varchar(50),
 cpu_ms int,
 cpu_pct int)

create table #IOPS (snap_time varchar(30),
 db_id int,
 db_name varchar(50),
 reads int,
 writes int,
 total_io int)

declare @cntr int
 set @cntr = 0
 while (@cntr) < 24 --set number of 1-hour loops to perform here.
 begin;

WITH DB_CPU_Stats
 AS
 (
 SELECT convert(varchar, getdate(), 120) AS ts,
 DatabaseID, DB_Name(DatabaseID) AS [DatabaseName],
 SUM(total_worker_time) AS [CPU_Time_Ms]
 FROM sys.dm_exec_query_stats AS qs
 CROSS APPLY (
 SELECT CONVERT(int, value) AS [DatabaseID]
 FROM sys.dm_exec_plan_attributes(qs.plan_handle)
 WHERE attribute = N'dbid') AS F_DB
 GROUP BY DatabaseID
 )
 insert into #CPU (row_num,snap_time,db_name,cpu_ms,cpu_pct)
 SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [row_num],
 ts, DatabaseName,
 [CPU_Time_Ms],
 CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPUPercent]
 FROM DB_CPU_Stats
 --WHERE DatabaseID > 4 -- system databases
 --AND DatabaseID <> 32767 -- ResourceDB
 ORDER BY row_num OPTION (RECOMPILE);

WITH D
 AS(
 SELECT
 convert(varchar, getdate(), 120) AS ts,
 database_id,DB_NAME(database_id) AS Name,
 SUM(num_of_reads) AS IO_Reads,
 SUM(num_of_writes) AS IO_Writes,
 SUM(num_of_reads + num_of_writes) AS Total_IO
 FROM sys.dm_io_virtual_file_stats(NULL, NULL)
 GROUP BY database_id,DB_NAME(database_id))
 insert into #IOPS (snap_time,db_id,db_name,reads,writes,total_io)
 SELECT
 D.ts, D.database_id, D.Name,
 SUM(D.IO_Reads) - SUM(L.num_of_reads) AS Data_Reads,
 SUM(D.IO_Writes) - SUM(L.num_of_writes) AS Data_Writes,
 SUM(D.IO_Reads+D.IO_Writes) - SUM(L.num_of_reads+L.num_of_writes) AS Total_IO
 FROM D
 JOIN sys.dm_io_virtual_file_stats(NULL, 2) L
 ON D.database_id = L.database_id
 GROUP BY D.ts,D.database_id, D.Name
 ORDER BY D.database_id;

waitfor delay '01:00:00' --change this to determine the interval between snapshots
 set @cntr = @cntr + 1

end

select db_name, avg(cpu_pct) as AVG_CPU
 from #CPU
 where db_name is not null
 group by db_name
 order by db_name;

select DB_NAME, snap_time, MAX(cpu_pct) as MAX_CPU
 from #CPU
 group by db_name, snap_time
 having MAX(cpu_pct) > 0
 order by MAX(cpu_pct) desc

select db_name, min(total_io) AS MIN_IO, max(total_io) AS MAX_IO, avg(total_io) AS AVG_IO
 from #IOPS
 group by db_name
 order by db_name;

select snap_time, db_name, reads, writes, total_io
 from #IOPS
 where total_io = (select max(total_io) from #IOPS);

drop table #CPU;

drop table #IOPS;

Keep your Oracle binaries!

I am a pack rat.  I admit it.  I rarely throw away old software or IT books.  I still have Oracle version 6 books.  The last time I got rid of software was when I threw out 3 boxes of 3.5″ floppy drives.  I still have old versions of Windows and other software on CD, though.  Not DVD, but CD.  Anyone need a copy of Windows NT 3.51?

My point is that we typically don’t think about preserving Oracle installation media files after the installation is concluded.  More often they are removed to reclaim space in a staging area with the thought that we can always download them again.

After the installation, flash forward to the point where upgrades have not occurred and the hardware is starting to show its age.  Then, just before the work day begins, a failure on a legacy storage appliance causes all the production databases to go down.

If you are lucky, there is a disaster recovery plan in place.  You are even luckier if it has been tested.  At the end of the failure, there are going to be lessons learned and plan revisions.

I recently experienced just such an occurrence at a client site.  A legacy storage appliance did fail, taking the production databases with it.  You are probably thinking that something like this very rarely, if ever, happens but I have seen network storage appliance failure of this kind twice within the last five years at different places and with different storage appliance makers.

After the initial smoke cleared, three options for recovery were available.  In order of preference, they were recover the storage appliance, rebuild servers and databases and recover from backups, and fail over to a disaster recovery site.

While the first option was in progress, it was discovered that the disaster recovery site option would only bring designated critical systems back online, but not every production database.  It was further discovered that this option would only allow fail over and not fail back and not allow running systems from sites other than the DR site.  As such, this option was abandoned.

This left the option of rebuilding servers and databases and recovering from backups while the storage appliance was being worked on.  Unfortunately, a recent acquisition had brought many databases running on unsupported versions of Oracle into the environment.  Now there was a scramble to secure the installation media for these versions.

Installation media is available through Oracle Technology Network (https://www.oracle.com/technetwork) or Oracle Software Delivery Cloud (https://edelivery.oracle.com).  However, as of the writing of this blog, versions 11g release 1 and 10g release 2 are no longer available for direct download.  You can request previous versions of the installation media using the instructions in My Oracle Support (MOS) note 1071023.1.  Oracle provides this statement (links included) on the Oracle Technology Network site when viewing Oracle Database software downloads:

Oracle Database 10.2 and 11.1 are no longer available for download. The software is available as a media or FTP request for those customers who own a valid Oracle Database product license for any edition. To request access to these releases, follow the instructions in Oracle Support Document 1071023.1 (Requesting Physical Shipment or Download URL for Software Media) from My Oracle Support. NOTE: for Oracle Database 10.2, you should request 10.2.0.1 even if you want to install a later patch set. Once you install 10.2.0.1 you can then apply any 10.2 patch set. Similarly, for 11.1 request 11.1.0.6 which must be applied before installing 11.1.0.7. Patch sets can be downloaded from the Patches and Updates tab on My Oracle Support.

In most of the recent client sites I have been to, virtual machines are the standard, replacing individual servers.  These VMs are hosted on large appliances that allow near instantaneous recovery in the event of a failure.  In non-virtual environments, I have seen backups performed at the OS level, where the Oracle binaries are typically installed.  In either of these cases, it may not be necessary to keep copies of the Oracle installation media.

My recommendation is to keep not only the installation media of every Oracle software product in your environment, but also keep copies of all patches applied.  With storage as cheap and accessible as it is now, there is no  real reason not to.  You never know when you will need it again.

SQL Server Health Check v3

My health check script continues to evolve.

–sql_server_health_check_v3.sql
–v3
–This is a non-intrusive script written to give an overall informational view of a
–SQL Server 2005-2016(CTP3) server instance for the purpose of first-time review.

–Version 3 additions
–User statistics identification
–License information
–Database data and log size with total

/*
Information gathered
-Node name
-License information
-Product Version, level, and Edition
-Instance parameters
-Start time and up time
-Database listing
-Database uptime
-Database data and log size with total
-Database file size and growth settings
-Is this a Cluster Node?
-Nodes in Cluster
-Is AlwaysOn enabled (2012 and above)?
-AlwaysOn status
-Memory usage per database
-Memory usage of in-memory OLTP tables
-Last backup time per database
-No log backups for FULL or BULK_LOGGED recovery model databases in last 30 days
-Databases with no backups at all in the last 30 says
-Backups for the previous week per database
-Jobs that failed in the last 24 hours
-Missing indexes
-Duplicate indexes
-High index fragmentation check
-Wait stats
-Users and roles
-Job information
-Existing linked server listing
-User statistics identification

*/
use master
GO
———————————————————-Node name

SELECT SERVERPROPERTY(‘ComputerNamePhysicalNetBIOS’) AS [CurrentNodeName];
———————————————————-Product Version, level, and Edition

SELECT SERVERPROPERTY(‘productversion’) AS ProductVersion,
SERVERPROPERTY (‘productlevel’) AS ProductLevel
SERVERPROPERTY (‘edition’) AS Edition;

———————————————————-License information

print N’License information’;

SELECT SERVERPROPERTY(‘LicenseType’) AS LICENSE_TYPE,
ISNULL(SERVERPROPERTY(‘NumLicenses’),0) AS NUM_LICENCES;

———————————————————-Instance parameters

print N’Instance Parameter’;
SELECT *
FROM sys.configurations
ORDER BY name ;
———————————————————-Database listing

print N’Database list with Status and Recovery Model’;

SELECT substring(name,1,40) AS name, substring(state_desc,1,20) AS STATE,
substring(recovery_model_desc,1,20) AS RECOVERY_MODEL
FROM sys.databases
order by name;

———————————————————-Database startup time

print N’Start time’;

SELECT DATEADD(ms,-sample_ms,GETDATE() )AS StartTime
FROM sys.dm_io_virtual_file_stats(1,1);
———————————————————-Database start time uptime

print N’Up time’;
DECLARE @server_start_time DATETIME,
@seconds_diff INT,
@years_online INT,
@days_online INT,
@hours_online INT,
@minutes_online INT,
@seconds_online INT ;

SELECT @server_start_time = login_time
FROM master.sys.sysprocesses
WHERE spid = 1 ;

SELECT @seconds_diff = DATEDIFF(SECOND, @server_start_time, GETDATE()),
@years_online = @seconds_diff / 31536000,
@seconds_diff = @seconds_diff % 31536000,
@days_online = @seconds_diff / 86400,
@seconds_diff = @seconds_diff % 86400,
@hours_online = @seconds_diff / 3600,
@seconds_diff = @seconds_diff % 3600,
@minutes_online = @seconds_diff / 60,
@seconds_online = @seconds_diff % 60 ;

SELECT @server_start_time AS server_start_time,
@years_online AS years_online,
@days_online AS days_online,
@hours_online AS hours_online,
@minutes_online AS minutes_online,
@seconds_online AS seconds_online ;
SELECT substring(name,1,40) AS name, substring(state_desc,1,20) AS STATE,
substring(recovery_model_desc,1,20) AS RECOVERY_MODEL
FROM sys.databases
order by name;

———————————————————-Database data and log size with total

print N’Data and Log Size with Total’;
with fs
as
(
select database_id, type, size * 8.0 / 1024 size
from sys.master_files
)
select
name,
(select sum(size) from fs where type = 0 and fs.database_id = db.database_id) DataFileSizeMB,
(select sum(size) from fs where type = 1 and fs.database_id = db.database_id) LogFileSizeMB,
(select sum(size) from fs where type = 0 and fs.database_id = db.database_id) +
(select sum(size) from fs where type = 1 and fs.database_id = db.database_id) AS Total_MB
from sys.databases db;

–Grand total of ALL data and log files as one value
select SUM(size*8.0)/1024 AS Total_MB
from sys.master_files;
———————————————————-Database file size and growth settings

print N’Size and Growth’;
select substring(b.name,1,40) AS DB_Name, substring(a.name,1,40) AS Logical_name,
substring(a.filename,1,100) AS File_Name,
cast((a.size * 8.00) / 1024 as numeric(12,2)) as DB_Size_in_MB,
case when a.growth > 100 then ‘In MB’ else ‘In Percentage’ end File_Growth,
cast(case when a.growth > 100 then (a.growth * 8.00) / 1024
else (((a.size * a.growth) / 100) * 8.00) / 1024
end as numeric(12,2)) File_Growth_Size_in_MB,
case when ( maxsize = -1 or maxsize=268435456 ) then ‘AutoGrowth Not Restricted’ else ‘AutoGrowth Restricted’ end AutoGrowth_Status
from sysaltfiles a
join sysdatabases b on a.dbid = b.dbid
where DATABASEPROPERTYEX(b.name, ‘status’) = ‘ONLINE’
order by b.name;
———————————————————-Is this a Cluster Node?

SELECT ‘Clustered’, case when SERVERPROPERTY(‘IsClustered’) = 0 then ‘No’
else ‘Yes’ end;

———————————————————-Nodes in Cluster

print N’Cluster Nodes’;

SELECT * FROM fn_virtualservernodes();
———————————————————-Is AlwaysOn enabled (2012 and above)?

SELECT ‘AlwaysOn’, case when SERVERPROPERTY(‘IsHadrEnabled’) = 0 then ‘No’
when SERVERPROPERTY(‘IsHadrEnabled’) = 1 then ‘Yes’
else SERVERPROPERTY(‘IsHadrEnabled’) end;
———————————————————-AlwaysOn status

declare @c int;
declare @rd nvarchar(60);
declare @osd nvarchar(60);
declare @rhd nvarchar(60);
declare @shd nvarchar(60);
declare @csd nvarchar(60);
select @c = COUNT(name)
from sys.all_objects
where name = ‘dm_hadr_availability_replica_states’;
if @c = 0
print N’No AlwaysOn Status’;
else
select @rd = role_desc, @osd= case when operational_state_desc is null then ‘Replica is not local’
else operational_state_desc end,
@rhd = recovery_health_desc, @shd = synchronization_health_desc,
@csd = connected_state_desc
from sys.dm_hadr_availability_replica_states;
print @rd
print @osd
print @rhd
print @shd
print @csd
———————————————————-Memory usage per database

print N’Memory Usage per User Database’;
SELECT
substring(DB_NAME(database_id),1,40) AS [Database Name]
,COUNT(*) * 8/1024.0 AS [Cached Size (MB)]
FROM
sys.dm_os_buffer_descriptors
WHERE
database_id > 4
AND database_id <> 32767
AND db_name(database_id) <> ‘SSISDB’
GROUP BY DB_NAME(database_id)
ORDER BY [Cached Size (MB)] DESC OPTION (RECOMPILE);

———————————————————-Memory usage of in-memory OLTP tables

print N’In-memory OLTP table usage’;
SELECT object_name(object_id) AS Name, *
FROM sys.dm_db_xtp_table_memory_stats;
———————————————————-Last backup time per database

SELECT substring(sdb.Name,1,40) AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),’-‘) AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
where sdb.Name <> ‘tempdb’
GROUP BY sdb.Name;
———————————————————-No log backups for FULL or BULK_LOGGED recovery model databases in last 30 days
print N’Databases with FULL or BULK_LOGGED recovery model and no log backups in last 30 days’;
SELECT name AS at_risk_database
FROM sys.databases
where recovery_model_desc in(‘FULL’,’BULK_LOGGED’)
and name not in(
SELECT
msdb.dbo.backupset.database_name AS DBName
FROM msdb.dbo.backupmediafamily
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id
WHERE (CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= GETDATE() – 30)
and msdb..backupset.type = ‘L’
group by msdb.dbo.backupset.database_name
);

———————————————————-Databases with no backups at all in the last 30 says

print N’Databases with NO backups in last 30 days’;

SELECT name AS at_risk_database
FROM sys.databases
where name <> ‘tempdb’
and name not in(
SELECT
substring(msdb.dbo.backupset.database_name,1,40) AS DBName
FROM msdb.dbo.backupmediafamily
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id
WHERE (CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= GETDATE() – 30)
group by msdb.dbo.backupset.database_name
);
———————————————————-Backups for the previous week per database

print N’All backups for previous week’;

SELECT
CONVERT(CHAR(40), SERVERPROPERTY(‘Servername’)) AS Server,
substring(msdb.dbo.backupset.database_name,1,40) AS DBName,
msdb.dbo.backupset.backup_start_date,
msdb.dbo.backupset.backup_finish_date,
msdb.dbo.backupset.expiration_date,
CASE msdb..backupset.type
WHEN ‘D’ THEN ‘Database’
WHEN ‘L’ THEN ‘Log’
WHEN ‘F’ THEN ‘File’
WHEN ‘P’ THEN ‘Partial’
WHEN ‘I’ THEN ‘Differential database’
WHEN ‘G’ THEN ‘Differential file’
WHEN ‘Q’ THEN ‘Differential partial’
WHEN NULL THEN msdb..backupset.type
END AS backup_type,
msdb.dbo.backupset.backup_size,
substring(msdb.dbo.backupmediafamily.logical_device_name,1,50) AS logical_device_name,
substring(msdb.dbo.backupmediafamily.physical_device_name,1,50) AS physical_device_name,
substring(msdb.dbo.backupset.name,1,50) AS backupset_name,
substring(msdb.dbo.backupset.description,1,50) AS description
FROM msdb.dbo.backupmediafamily
INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id
WHERE (CONVERT(datetime, msdb.dbo.backupset.backup_start_date, 102) >= GETDATE() – 7)
ORDER BY
msdb.dbo.backupset.database_name,
msdb.dbo.backupset.backup_finish_date;
———————————————————-Jobs that failed in the last 24 hours

print N’Jobs Failing in last 24 hours’;

———————————————————-Variable Declarations
DECLARE @PreviousDate datetime
DECLARE @Year VARCHAR(4)
DECLARE @Month VARCHAR(2)
DECLARE @MonthPre VARCHAR(2)
DECLARE @Day VARCHAR(2)
DECLARE @DayPre VARCHAR(2)
DECLARE @FinalDate INT
———————————————————-Initialize Variables
SET @PreviousDate = DATEADD(dd, -1, GETDATE()) –Last 1 day
SET @Year = DATEPART(yyyy, @PreviousDate)
SELECT @MonthPre = CONVERT(VARCHAR(2), DATEPART(mm, @PreviousDate))
SELECT @Month = RIGHT(CONVERT(VARCHAR, (@MonthPre + 1000000000)),2)
SELECT @DayPre = CONVERT(VARCHAR(2), DATEPART(dd, @PreviousDate))
SELECT @Day = RIGHT(CONVERT(VARCHAR, (@DayPre + 1000000000)),2)
SET @FinalDate = CAST(@Year + @Month + @Day AS INT)
–Final Logic
SELECT substring(j.[name],1,40) AS JOB,
substring(s.step_name,1,40) AS Step,
h.step_id,
substring(h.step_name,1,40) AS Step,
h.run_date,
h.run_time,
h.sql_severity,
substring(h.message,1,100) AS Message,
h.server
FROM msdb.dbo.sysjobhistory h
INNER JOIN msdb.dbo.sysjobs j
ON h.job_id = j.job_id
INNER JOIN msdb.dbo.sysjobsteps s
ON j.job_id = s.job_id AND h.step_id = s.step_id
WHERE h.run_status = 0 –Failure
AND h.run_date > @FinalDate
ORDER BY h.instance_id DESC;

———————————————————-Missing indexes

print N’Missing Indexes’;
SELECT substring(so.name,1,40) AS Name
, (avg_total_user_cost * avg_user_impact) * (user_seeks + user_scans) as Impact
, ddmid.equality_columns
, ddmid.inequality_columns
, ddmid.included_columns
FROM sys.dm_db_missing_index_group_stats AS ddmigs
INNER JOIN sys.dm_db_missing_index_groups AS ddmig
ON ddmigs.group_handle = ddmig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details AS ddmid
ON ddmig.index_handle = ddmid.index_handle
INNER JOIN sys.objects so WITH (nolock)
ON ddmid.object_id = so.object_id
WHERE ddmigs.group_handle IN (
SELECT TOP (5000) group_handle
FROM sys.dm_db_missing_index_group_stats WITH (nolock)
ORDER BY (avg_total_user_cost * avg_user_impact)*(user_seeks+user_scans)DESC);

———————————————————-Duplicate indexes

print N’Duplicate Indexes’;

DECLARE @SCHEMANAME VARCHAR(30);
DECLARE @TABLENAME VARCHAR(127);
WITH ind_list AS(
select o.schema_id, i.object_id, i.index_id,
i.name, i.type_desc,
i.is_unique, i.is_primary_key,
STUFF( (SELECT ‘,’ + tc.name
FROM sys.index_columns ic
JOIN sys.columns tc
ON tc.column_id = ic.column_id AND
tc.object_id = ic.object_id
WHERE ic.object_id = i.object_id AND
ic.index_id = i.index_id
AND ic.is_included_column = 0
ORDER BY ic.index_column_id
FOR XML PATH (”) ),1,1,” ) index_columns,
STUFF( (SELECT ‘,’ + tc.name
FROM sys.index_columns ic
JOIN sys.columns tc
ON tc.column_id = ic.column_id AND
tc.object_id = ic.object_id
WHERE ic.object_id = i.object_id AND
ic.index_id = i.index_id
AND ic.is_included_column = 1
ORDER BY ic.index_column_id
FOR XML PATH (”) ),1,1,” ) include_columns
FROM sys.indexes i
JOIN sys.objects o ON o.object_id = i.object_id
WHERE i.index_id > 0 AND i.type_desc <> ‘XML’
AND object_name(i.object_id) LIKE @TABLENAME
AND i.is_disabled = 0
AND schema_name(o.schema_id) LIKE @SCHEMANAME )
SELECT substring(schema_name(included_indexes.schema_id),1,30) AS owner,
object_name(included_indexes.object_id) table_name,
(SELECT SUM(st.row_count) FROM sys.dm_db_partition_stats st
WHERE st.object_id = included_indexes.object_id
AND st.index_id < 2 ) num_rows,
included_indexes.name included_index_name,
included_indexes.index_columns included_index_columns,
included_indexes.include_columns
included_index_include_columns,
included_indexes.type_desc included_index_type,
included_indexes.is_unique included_index_uniqueness,
included_indexes.is_primary_key included_index_PK,
(SELECT SUM(a.total_pages) * 8 FROM sys.allocation_units a
JOIN sys.partitions p ON a.container_id = p.partition_id
WHERE p.object_id = included_indexes.object_id AND
p.index_id = included_indexes.index_id
) included_index_size_kb,
including_indexes.name including_index_name,
including_indexes.index_columns including_index_columns,
including_indexes.include_columns
including_index_include_columns,
including_indexes.type_desc including_index_type,
including_indexes.is_unique including_index_uniqueness,
including_indexes.is_primary_key including_index_PK,
(SELECT SUM(a.total_pages) * 8 FROM sys.allocation_units a
JOIN sys.partitions p ON a.container_id = p.partition_id
WHERE p.object_id = including_indexes.object_id AND
p.index_id = including_indexes.index_id
) including_index_size_kb
FROM ind_list included_indexes
JOIN ind_list including_indexes
ON including_indexes.object_id = included_indexes.object_id
JOIN sys.partitions ing_p
ON ing_p.object_id = including_indexes.object_id AND
ing_p.index_id = including_indexes.index_id
JOIN sys.allocation_units ing_a
ON ing_a.container_id = ing_p.partition_id
WHERE including_indexes.index_id <> included_indexes.index_id
AND LEN(included_indexes.index_columns) <=
LEN(including_indexes.index_columns)
AND included_indexes.index_columns + ‘,’ =
SUBSTRING(including_indexes.index_columns,1,
LEN(included_indexes.index_columns + ‘,’))
ORDER BY 2 DESC;

———————————————————-High index fragmentation check

print N’Index with HIGH Fragmentation’;

EXEC sp_MSforeachdb ‘
USE [?]
SELECT ”?” AS DB_NAME,
QUOTENAME(sysind.name) AS [index_name],
indstat.*
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, ”LIMITED”)
AS indstat
INNER JOIN sys.indexes sysind ON indstat.object_id = sysind.object_id AND
indstat.index_id = sysind.index_id
where avg_fragmentation_in_percent >= 30
ORDER BY avg_fragmentation_in_percent DESC;

use master
GO
———————————————————-Wait stats

print N’Wait Stats’;

SELECT *
FROM sys.dm_os_wait_stats
where wait_time_ms > 10000
ORDER BY wait_time_ms DESC;
———————————————————-Users and roles

print N’Users and Roles’;

WITH Roles_CTE(Role_Name, Username)
AS
(
SELECT
User_Name(sm.[groupuid]) as [Role_Name],
user_name(sm.[memberuid]) as [Username]
FROM [sys].[sysmembers] sm
)

SELECT
Roles_CTE.Role_Name,
[DatabaseUserName] = princ.[name],
[UserType] = CASE princ.[type]
WHEN ‘S’ THEN ‘SQL User’
WHEN ‘U’ THEN ‘Windows User’
WHEN ‘G’ THEN ‘Windows Group’
WHEN ‘A’ THEN ‘Application Role’
WHEN ‘R’ THEN ‘Database Role’
WHEN ‘C’ THEN ‘User mapped to a certificate’
WHEN ‘K’ THEN ‘User mapped to an asymmetric key’
END
FROM
sys.database_principals princ
JOIN Roles_CTE on Username = princ.name
where princ.type in (‘S’, ‘U’, ‘G’, ‘A’, ‘R’, ‘C’, ‘K’)
ORDER BY princ.name;
———————————————————-Job information

print N’Job Information’;
SELECT [JobName] = [jobs].[name]
,[Category] = [categories].[name]
,[Owner] = SUSER_SNAME([jobs].[owner_sid])
,[Enabled] = CASE [jobs].[enabled] WHEN 1 THEN ‘Yes’ ELSE ‘No’ END
,[Scheduled] = CASE [schedule].[enabled] WHEN 1 THEN ‘Yes’ ELSE ‘No’ END
,[Description] = [jobs].[description]
,[Occurs] =
CASE [schedule].[freq_type]
WHEN 1 THEN ‘Once’
WHEN 4 THEN ‘Daily’
WHEN 8 THEN ‘Weekly’
WHEN 16 THEN ‘Monthly’
WHEN 32 THEN ‘Monthly relative’
WHEN 64 THEN ‘When SQL Server Agent starts’
WHEN 128 THEN ‘Start whenever the CPU(s) become idle’
ELSE ”
END
,[Occurs_detail] =
CASE [schedule].[freq_type]
WHEN 1 THEN ‘O’
WHEN 4 THEN ‘Every ‘ + CONVERT(VARCHAR, [schedule].[freq_interval]) + ‘ day(s)’
WHEN 8 THEN ‘Every ‘ + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ‘ weeks(s) on ‘ +
LEFT(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN ‘Sunday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN ‘Monday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN ‘Tuesday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN ‘Wednesday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN ‘Thursday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN ‘Friday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN ‘Saturday, ‘ ELSE ” END ,
LEN(
CASE WHEN [schedule].[freq_interval] & 1 = 1 THEN ‘Sunday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 2 = 2 THEN ‘Monday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 4 = 4 THEN ‘Tuesday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 8 = 8 THEN ‘Wednesday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 16 = 16 THEN ‘Thursday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 32 = 32 THEN ‘Friday, ‘ ELSE ” END +
CASE WHEN [schedule].[freq_interval] & 64 = 64 THEN ‘Saturday, ‘ ELSE ” END
) – 1
)
WHEN 16 THEN ‘Day ‘ + CONVERT(VARCHAR, [schedule].[freq_interval]) + ‘ of every ‘ + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ‘ month(s)’
WHEN 32 THEN ‘The ‘ +
CASE [schedule].[freq_relative_interval]
WHEN 1 THEN ‘First’
WHEN 2 THEN ‘Second’
WHEN 4 THEN ‘Third’
WHEN 8 THEN ‘Fourth’
WHEN 16 THEN ‘Last’
END +
CASE [schedule].[freq_interval]
WHEN 1 THEN ‘ Sunday’
WHEN 2 THEN ‘ Monday’
WHEN 3 THEN ‘ Tuesday’
WHEN 4 THEN ‘ Wednesday’
WHEN 5 THEN ‘ Thursday’
WHEN 6 THEN ‘ Friday’
WHEN 7 THEN ‘ Saturday’
WHEN 8 THEN ‘ Day’
WHEN 9 THEN ‘ Weekday’
WHEN 10 THEN ‘ Weekend Day’
END + ‘ of every ‘ + CONVERT(VARCHAR, [schedule].[freq_recurrence_factor]) + ‘ month(s)’
ELSE ”
END
,[Frequency] =
CASE [schedule].[freq_subday_type]
WHEN 1 THEN ‘Occurs once at ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’)
WHEN 2 THEN ‘Occurs every ‘ +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ‘ Seconds(s) between ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’) + ‘ and ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’)
WHEN 4 THEN ‘Occurs every ‘ +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ‘ Minute(s) between ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’) + ‘ and ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’)
WHEN 8 THEN ‘Occurs every ‘ +
CONVERT(VARCHAR, [schedule].[freq_subday_interval]) + ‘ Hour(s) between ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_start_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’) + ‘ and ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [schedule].[active_end_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’)
ELSE ”
END
,[AvgDurationInSec] = CONVERT(DECIMAL(10, 2), [jobhistory].[AvgDuration])
,[Next_Run_Date] =
CASE [jobschedule].[next_run_date]
WHEN 0 THEN CONVERT(DATETIME, ‘1900/1/1’)
ELSE CONVERT(DATETIME, CONVERT(CHAR(8), [jobschedule].[next_run_date], 112) + ‘ ‘ +
STUFF(STUFF(RIGHT(‘000000’ + CONVERT(VARCHAR(8), [jobschedule].[next_run_time]), 6), 5, 0, ‘:’), 3, 0, ‘:’))
END
FROM [msdb].[dbo].[sysjobs] AS [jobs] WITh(NOLOCK)
LEFT OUTER JOIN [msdb].[dbo].[sysjobschedules] AS [jobschedule] WITh(NOLOCK)
ON [jobs].[job_id] = [jobschedule].[job_id]
LEFT OUTER JOIN [msdb].[dbo].[sysschedules] AS [schedule] WITh(NOLOCK)
ON [jobschedule].[schedule_id] = [schedule].[schedule_id]
INNER JOIN [msdb].[dbo].[syscategories] [categories] WITh(NOLOCK)
ON [jobs].[category_id] = [categories].[category_id]
LEFT OUTER JOIN
( SELECT [job_id], [AvgDuration] = (SUM((([run_duration] / 10000 * 3600) +
(([run_duration] % 10000) / 100 * 60) +
([run_duration] % 10000) % 100)) * 1.0) / COUNT([job_id])
FROM [msdb].[dbo].[sysjobhistory] WITh(NOLOCK)
WHERE [step_id] = 0
GROUP BY [job_id]
) AS [jobhistory]
ON [jobhistory].[job_id] = [jobs].[job_id];
———————————————————-Existing linked server listing
print N’Linked Server Information’;
declare @x int;
select @x = COUNT(name)
from sys.all_objects
where name = ‘Servers’;
if @x <> 0
SELECT *
–c.name, provider, data_source, is_remote_login_enabled, b.modify_date
FROM sys.Servers a
LEFT OUTER JOIN sys.linked_logins b ON b.server_id = a.server_id
LEFT OUTER JOIN sys.server_principals c ON c.principal_id = b.local_principal_id
where a.server_id <> 0;
else
exec sp_linkedservers;
———————————————————-User statistics identification

print N’User statistics’;

select s.name as STATS_NAME, SCHEMA_NAME(ob.Schema_id) AS SCHEMA_NAME, OBJECT_NAME(s.object_id) AS TABLE_NAME
FROM sys.stats s
INNER JOIN sys.Objects ob ON ob.Object_id = s.object_id
WHERE SCHEMA_NAME(ob.Schema_id) <> ‘sys’
AND Auto_Created = 0 AND User_Created = 1;