Showing posts with label sql. Show all posts
Showing posts with label sql. Show all posts

Friday, June 26, 2020

How to transfer logins and passwords between instances of SQL Server



Applies to: Microsoft SQL Server 2005 Standard EditionMicrosoft SQL Server 2005 Workgroup EditionMicrosoft SQL Server 2005 Developer EditionMicrosoft SQL Server 2005 Enterprise EditionSQL Server 2008 StandardSQL Server 2008 WorkgroupSQL Server 2008 DeveloperSQL Server 2008 EnterpriseSQL Server 2012 StandardSQL Server 2012 DeveloperSQL Server 2012 EnterpriseSQL Server 2014 DeveloperSQL Server 2014 EnterpriseSQL Server 2016 StandardSQL Server 2016 DeveloperSQL Server 2016 EnterpriseSQL Server 2017 on Windows (all editions)

---------------------------------


EXEC sp_help_revlogin


---------------------------------

USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
  DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
    @binvalue varbinary(256),
    @hexvalue varchar (514) OUTPUT
AS
DECLARE @charvalue varchar (514)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
  DECLARE @tempint int
  DECLARE @firstint int
  DECLARE @secondint int
  SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
  SELECT @firstint = FLOOR(@tempint/16)
  SELECT @secondint = @tempint - (@firstint*16)
  SELECT @charvalue = @charvalue +
    SUBSTRING(@hexstring, @firstint+1, 1) +
    SUBSTRING(@hexstring, @secondint+1, 1)
  SELECT @i = @i + 1
END

SELECT @hexvalue = @charvalue
GO
 
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
  DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @type varchar (1)
DECLARE @hasaccess int
DECLARE @denylogin int
DECLARE @is_disabled int
DECLARE @PWD_varbinary  varbinary (256)
DECLARE @PWD_string  varchar (514)
DECLARE @SID_varbinary varbinary (85)
DECLARE @SID_string varchar (514)
DECLARE @tmpstr  varchar (1024)
DECLARE @is_policy_checked varchar (3)
DECLARE @is_expiration_checked varchar (3)

DECLARE @defaultdb sysname
 
IF (@login_name IS NULL)
  DECLARE login_curs CURSOR FOR

      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name <> 'sa'
ELSE
  DECLARE login_curs CURSOR FOR


      SELECT p.sid, p.name, p.type, p.is_disabled, p.default_database_name, l.hasaccess, l.denylogin FROM 
sys.server_principals p LEFT JOIN sys.syslogins l
      ON ( l.name = p.name ) WHERE p.type IN ( 'S', 'G', 'U' ) AND p.name = @login_name
OPEN login_curs

FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
IF (@@fetch_status = -1)
BEGIN
  PRINT 'No login(s) found.'
  CLOSE login_curs
  DEALLOCATE login_curs
  RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated ' + CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
  IF (@@fetch_status <> -2)
  BEGIN
    PRINT ''
    SET @tmpstr = '-- Login: ' + @name
    PRINT @tmpstr
    IF (@type IN ( 'G', 'U'))
    BEGIN -- NT authenticated account/group

      SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' FROM WINDOWS WITH DEFAULT_DATABASE = [' + @defaultdb + ']'
    END
    ELSE BEGIN -- SQL Server authentication
        -- obtain password and sid
            SET @PWD_varbinary = CAST( LOGINPROPERTY( @name, 'PasswordHash' ) AS varbinary (256) )
        EXEC sp_hexadecimal @PWD_varbinary, @PWD_string OUT
        EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
 
        -- obtain password policy state
        SELECT @is_policy_checked = CASE is_policy_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
        SELECT @is_expiration_checked = CASE is_expiration_checked WHEN 1 THEN 'ON' WHEN 0 THEN 'OFF' ELSE NULL END FROM sys.sql_logins WHERE name = @name
 
            SET @tmpstr = 'CREATE LOGIN ' + QUOTENAME( @name ) + ' WITH PASSWORD = ' + @PWD_string + ' HASHED, SID = ' + @SID_string + ', DEFAULT_DATABASE = [' + @defaultdb + ']'

        IF ( @is_policy_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_POLICY = ' + @is_policy_checked
        END
        IF ( @is_expiration_checked IS NOT NULL )
        BEGIN
          SET @tmpstr = @tmpstr + ', CHECK_EXPIRATION = ' + @is_expiration_checked
        END
    END
    IF (@denylogin = 1)
    BEGIN -- login is denied access
      SET @tmpstr = @tmpstr + '; DENY CONNECT SQL TO ' + QUOTENAME( @name )
    END
    ELSE IF (@hasaccess = 0)
    BEGIN -- login exists but does not have access
      SET @tmpstr = @tmpstr + '; REVOKE CONNECT SQL TO ' + QUOTENAME( @name )
    END
    IF (@is_disabled = 1)
    BEGIN -- login is disabled
      SET @tmpstr = @tmpstr + '; ALTER LOGIN ' + QUOTENAME( @name ) + ' DISABLE'
    END
    PRINT @tmpstr
  END

  FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @type, @is_disabled, @defaultdb, @hasaccess, @denylogin
   END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO

Thursday, June 25, 2020

How to Configure Database Mail

A. Prerequisite Checks and Steps

SMTP Server Info: you’re going to need the fully qualified name, port information, and authentication information for your smtp server. Get this from your sysadmin so you don’t stall out along the way.

SQL Agent Operator: you may want to create an operator before you set this all up. You’ll use it here in your final test. (Don’t worry, that’s fast.)

Setting Checks: There are a couple things we like to look at before trying to configure Database Mail that can throw a real monkey in your wrench.

  1. Make sure Service Broker is still enabled in msdb (it is by default)
  2. Make sure SQL is configured to use the Database Mail XPs (it is NOT by default)

Here’s code to check those things:

Here’s an example of the results that come back:


Picture4

1 & 1

What if Someone Turned Off Service Broker in msdb?

If for some reason Service Broker isn’t enabled, you may have larger issues than this to worry about:

  • Are you using an Edition of SQL Server that supports Database Mail?
  • Was msdb ever restored from backup?

You need to ask these questions before enabling it.

How to Enable Database Mail Extended Procedures – TSQL Option

Reconfiguring your server to use the Database Mail XPs is straightforward. You can do this using TSQL, or you can walk through the wizard below. (It will prompt you if you need to make this change.)

B. Configuring Database Mail Using the Wizard

In Object Explorer, expand Management and right click Database Mail:

Picture5

To Boldly Get Bolded So You Know Exactly Where to Click

Click ‘Next’, then click the first option to set up Database Mail.

Step 1: Create a Profile

Name your profile, then click ‘Add’ to add an account:

Picture6

The more descriptive the better, since you may want multiple profiles for different purposes.

STEP 2: Create An Account

When adding an account, specify:

  • Email address: Most people use SQLSERVER01@yourdomain.com
  • Display name: Most people use the SQL Server’s name here, like SQLSERVER01
  • Reply email: Most people use DONOTREPLY@yourdomain.com
  • Server name: this is the smtp server you’re using. Don’t use gmail for production servers, the screenshot is just an example. Seriously.
  • Port and your authentication options. This varies by email service.

Picture7

Ask your sysadmin for the details of your Exchange server.

Remember to use a smpt server or service you trust; these emails will be vital to monitoring your server’s health.

C. Send a Test Email

Right click on “Database Mail” in Object Explorer. Select “Send a Test Email.” Fill out the helpful little form and make sure it works.

If it doesn’t work, there’s a problem in your setup. Right click “Database Mail” again and select “View Database Mail Log” to go hunting and find out where the issue is.

D. Enable Database Mail on the SQL Server Agent

You’re almost there, we promise. At this point your SQL Server can send mail, but the SQL Server Agent can’t yet. You need to tell it how you want it to use Database Mail for it to have powers to alert you about problems.

Right click on the SQL Server Agent and select properties, like this:

SQL Server Agent Properties

Now Click on the Alert System Tab

This is where you tell the SQL Server Agent what database mail profile to use. Enable the mail profile, then select your mail profile. You may also want to set up your failsafe operator right now. Then click OK.

SQL Agent Alert System

Restart the SQL Server Agent Service to Make That Take Effect

The SQL Server Agent is a little slow to learn: it won’t be able to use database mail until you restart the Agent service. Important reminders:

  • Note that we aren’t talking about the whole SQL Server itself: only the Agent service
  • Check if any jobs are running before restarting the SQL Server Agent Service. It will kill the jobs, and won’t automatically restart them, so you may want to wait until a quiet time when jobs aren’t running to do this step.

E. Test Your Work

You’ve come a long way. Here’s how to revel in your success:

  1. Create a SQL Server agent job named ‘Test’
  2. Give it a single step named ‘Hi’ which executes: print ‘I love Prince’
  3. Set the step to notify an operator on completion of the job
  4. Run the job
  5. Get the email
  6. Delete the job

Transaction Log Management


dbcc sqlperf (logspace)


SELECT name
, state_desc
, recovery_model_desc
, log_reuse_wait_desc
FROM sys.databases

MSDB Indexes


Oldest backupsets:

SELECT min(backup_start_date)
FROM msdb.dbo.backupset 


------------------------

use msdb
go

--backupset

Create index IX_backupset_backup_set_id on backupset(backup_set_id)
go

Create index IX_backupset_backup_set_uuid on backupset(backup_set_uuid)
go

Create index IX_backupset_media_set_id on backupset(media_set_id)
go

Create index IX_backupset_backup_finish_date on backupset(backup_finish_date)
go

Create index IX_backupset_backup_start_date on backupset(backup_start_date)
go

--backupmediaset

Create index IX_backupmediaset_media_set_id on backupmediaset(media_set_id)
go

--backupfile

Create index IX_backupfile_backup_set_id on backupfile(backup_set_id)
go

--backupmediafamily

Create index IX_backupmediafamily_media_set_id on backupmediafamily(media_set_id)
go

--restorehistory

Create index IX_restorehistory_restore_history_id on restorehistory(restore_history_id)
go

Create index IX_restorehistory_backup_set_id on restorehistory(backup_set_id)
go

--restorefile

Create index IX_restorefile_restore_history_id on restorefile(restore_history_id)
go

--restorefilegroup

Create index IX_restorefilegroup_restore_history_id on restorefilegroup(restore_history_id)
go

DatabaseIntegrityCheck - ALL_DATABASES

sqlcmd -E -S $(ESCAPE_SQUOTE(SRVR)) -d dbatoolbox -Q "EXECUTE [dbo].[DatabaseIntegrityCheck] @Databases = 'ALL_DATABASES', @PhysicalOnly = 'N', @LogToTable = 'Y'" -b

Olla Hallengren: IndexOptimize - USER_DATABASES

EXECUTE [dbo].[IndexOptimize]
@Databases = 'USER_DATABASES'
,@LogToTable = 'Y'
,@FragmentationLow = NULL
,@FragmentationMedium =  'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE'
,@FragmentationHigh = 'INDEX_REBUILD_ONLINE'
,@UpdateStatistics = 'ALL'
,@OnlyModifiedStatistics = 'Y'
,@MinNumberOfPages = 500
,@TimeLimit = 189900

Best Practices to maintain MSDB

1. sp_delete_backuphistory. This stored procedure deletes backup history. It will be run once per week, and configured to keep 30 days worth of history. Ola Hallengren (OH), our best practices suite, already has created a job, we simply need to schedule it.

2. sp_purge_job_history. This stored procedure deletes job history. It will be run once per week, and configured to keep 30 days worth of history.  OH already has created a job, we simply need to schedule it.

3. db_mail_cleanup. A job will be created to run the attached SQL ("db_mail_cleanup.txt"). It deletes emails sent by SQL Server after 30 days. 

db_mail_cleanup


DECLARE @DateBefore DATETIME 
SET @DateBefore = DATEADD(DAY, -30, GETDATE())

EXEC msdb.dbo.sysmail_delete_mailitems_sp @sent_before = @DateBefore --, @sent_status = 'sent'
EXEC msdb.dbo.sysmail_delete_log_sp @logged_before = @DateBefore



Justification

It contains backup history, job history and 'sent' mail items (by the built-in email client). Also, job history is stored in this database. Mail sent by the database is also stored in this database.

Having so much historical information is unnecessary, wastes storage and ultimately slows down backups (since new information will take longer to be inserted).

Backups (outside of 30 days) can be restored without having a history in msdb. Beyond 30 days, backup history, job history and email history has almost zero utility.

It is a best practice / recommendation to maintain msdb regularly by deleting unneeded job history, backup history and sent emails.

Implementation Plan

1.  enable a schedule for sp_delete_backuphistory to run at 21:00 on Fridays.
2.  enable a schedule for sp_purge_job_history to run at 21:30 on Fridays.
3. create a new job with the script for db_mail_cleanup, and create a schedule for it to run on 21:45 on Fridays.

Saturday, June 20, 2020

How to manually uninstall SQL Server

Applies to: All editions of Microsoft SQL Server 2008, Microsoft SQL Server 2008 R2, Microsoft SQL Server 2012, and Microsoft SQL Server 2014.

If you need to manually uninstall SQL Server 2005, please refer to Microsoft Support article KB909967.

If you are trying to uninstall SQL Server 2012 and you receive the error message "The operating system on the computer does not meet the minimum requirements for SQL Server 2012", please perform the following procedure as mentioned here:

Open File Explorer or WIndows Explorer and go to the folder C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\SQLServer2012.
Make a right click on the Setup.exe file, select Properties, click on the Compatibility tab, click on the checkbox name "Run this program in compatibility mode for", from the combo box select "Windows Vista (Service Pack 2)"
Go to Control Panel, Select "Uninstall a program" and uninstall SQL Server 2012.
If you are not able to uninstall SQL Server please try the procedure explained here.

You have tried everything and you are still unable to uninstall SQL Server, please to manually uninstall SQL Server using the following procedure:

1. Uninstall all SQL Server components you can using Control Panel -> Programs and Features

2. Backup the registry.

3. Delete the following keys in regedit:

--HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server

--HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer

4. Go to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall and delete all the sub-keys referencing SQL Server.

5. Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and delete all the keys referencing SQL Server.

6. Rename all the SQL Server folders in the computer like C:\Program Files\Microsoft SQL Server and subfolders.

Unhandled Exception installing SQL 2012 to Windows Server 2012 R2 machine

Trying to install SQL 2012 Developer Edition to a new Windows Server 2012 R2 (or Windows 8.1) machine I was getting an Unhandled Exception immediately after running the setup.exe.

Turns out this is due to a user.config file that gets created by conflicting versions of the .net framework as described in this Microsoft Article: http://support.microsoft.com/kb/2681562

Fortunately, there’s an easy fix:

Open this folder: %userprofile%\AppData\Local\Microsoft_Corporation\LandingPage.exe_StrongName_ryspccglaxmt4nhllj5z3thycltsvyyx\11.0.0.0

Delete the user.config file.

Re-run your setup and you’re good to go.

SQL Server Core Edition

Short: The regular "Enterprise" (non-"core") edition caps the cores at 20, period. The "core" edition has no such cap.