USE master;
GO

DECLARE @AccountName nVarchar(128)
SET @AccountName = 'DOMAIN\username' --MUST BE CHANGED TO YOUR DOMAIN AND VPS SERVICE ACCOUNT.

----------------------------------------------------------------------------------------------------------------
DECLARE @tSQL nVarchar(4000)

DECLARE @Version VarChar(100)
DECLARE @Major Int

SET @Version = Convert(VarChar(100), SERVERPROPERTY('productversion'))
SET @Major = SubString(@Version, 1, CharIndex('.', @Version) - 1)

IF NOT EXISTS (SELECT TOP 1 1 FROM sys.syslogins WHERE name = @AccountName)
BEGIN--IF
	SET @tSQL = 'CREATE LOGIN [' + @AccountName + '] FROM WINDOWS WITH DEFAULT_DATABASE = [master]'
	EXECUTE(@tSQL)
END--IF

SET @tSQL = 'GRANT CONTROL SERVER to [' + @AccountName + ']'
EXECUTE(@tSQL)

IF @Major >= 11
BEGIN--IF
	--Required for the creation of extended events.
	SET @tSQL = 'GRANT ALTER ANY EVENT SESSION to [' + @AccountName + ']'
	EXECUTE(@tSQL)
END--IF

SET @tSQL = 'GRANT ALTER TRACE to [' + @AccountName + ']'
EXECUTE(@tSQL)

IF @Major >= 10
BEGIN--IF
	SET @tSQL = 'GRANT ALTER ANY SERVER AUDIT to [' + @AccountName + ']'
	EXECUTE(@tSQL)
END--IF

SET @tSQL = 'GRANT VIEW SERVER STATE to [' + @AccountName + ']'
EXECUTE(@tSQL)

SET @tSQL = 'GRANT ALTER SERVER STATE to [' + @AccountName + ']'
EXECUTE(@tSQL)

SET @tSQL = 'IF EXISTS(SELECT TOP 1 1 FROM sys.databases WHERE name = ''?'' and state_desc like ''%ONLINE%'' AND is_read_only = 0)'
	+ ' BEGIN'
	+ ' USE [?];'
	+ 'IF NOT EXISTS(SELECT TOP 1 1 FROM sysusers WHERE name = ''' + @AccountName + ''')'
	+ '	CREATE USER [' + @AccountName + '] FOR LOGIN [' + @AccountName + '];'
	+ 'exec sp_addrolemember ''db_datareader'',''' + @AccountName + ''''
	+ ' END'
EXECUTE master.sys.sp_MSforeachdb @tSQL

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