func SetLocalServerName(db *sql.DB, serverName string) error {
	var currentServerName string
	err := db.QueryRow(`SELECT name FROM sys.servers WHERE server_id = 0`).Scan(&currentServerName)
	if err == nil && strings.EqualFold(currentServerName, serverName) {
		return nil
	}
	if err != nil && err != sql.ErrNoRows {
		return err
	}
	if err == nil {
		_, err = db.Exec("EXEC sp_dropserver ?", currentServerName)
		if err != nil {
			return err
		}
	}
	_, err = db.Exec("EXEC sp_addserver ?, local", serverName)
	return err
}
--------------------------------------------------------------------------------------
Function: SetLocalServerName

Description:
Sets the local server name to the given name via sp_dropserver + sp_addserver

Params:
db: A connection to a SQL Server instance.
serverName: The new name of the local server.
package mssqlcommon
import (
	"bufio"
	"database/sql"
	"fmt"
	"log"
	"net/url"
	"os"
	"strconv"
	"strings"
	"time"
)
type Diagnostics struct {
	System          bool
	Resource        bool
	QueryProcessing bool
}
type ServerHealth uint
const (
	ServerDownOrUnresponsive ServerHealth = 1
	ServerCriticalError ServerHealth = 3
	ServerModerateError ServerHealth = 4
	ServerAnyQualifiedError ServerHealth = 5
)
type ServerUnhealthyError struct {
	RawValue ServerHealth
	Inner    error
}
func (err *ServerUnhealthyError) Error() string {
	switch err.RawValue {
	case ServerAnyQualifiedError:
		return fmt.Sprintf("AnyQualified %s", err.Inner)
	case ServerModerateError:
		return fmt.Sprintf("Moderate %s", err.Inner)
	case ServerCriticalError:
		return fmt.Sprintf("Critical %s", err.Inner)
	case ServerDownOrUnresponsive:
		return fmt.Sprintf("Unresponsive or down %s", err.Inner)
	default:
		return fmt.Sprintf("Unknown (%d) %s", err.RawValue, err.Inner)
	}
}
type OcfExitCode int
var (
	OCF_ERR_CONFIGURED    OcfExitCode
	OCF_ERR_GENERIC       OcfExitCode
	OCF_ERR_ARGS          OcfExitCode
	OCF_ERR_PERM          OcfExitCode
	OCF_ERR_UNIMPLEMENTED OcfExitCode
	OCF_FAILED_MASTER     OcfExitCode
	OCF_NOT_RUNNING       OcfExitCode
	OCF_RUNNING_MASTER    OcfExitCode
	OCF_SUCCESS           OcfExitCode
)
func ImportOcfExitCodes() error {
	var err error
	OCF_ERR_CONFIGURED, err = importOcfExitCode("OCF_ERR_CONFIGURED")
	if err != nil {
		return err
	}
	OCF_ERR_GENERIC, err = importOcfExitCode("OCF_ERR_GENERIC")
	if err != nil {
		return err
	}
	OCF_ERR_ARGS, err = importOcfExitCode("OCF_ERR_ARGS")
	if err != nil {
		return err
	}
	OCF_ERR_PERM, err = importOcfExitCode("OCF_ERR_PERM")
	if err != nil {
		return err
	}
	OCF_ERR_UNIMPLEMENTED, err = importOcfExitCode("OCF_ERR_UNIMPLEMENTED")
	if err != nil {
		return err
	}
	OCF_FAILED_MASTER, err = importOcfExitCode("OCF_FAILED_MASTER")
	if err != nil {
		return err
	}
	OCF_NOT_RUNNING, err = importOcfExitCode("OCF_NOT_RUNNING")
	if err != nil {
		return err
	}
	OCF_RUNNING_MASTER, err = importOcfExitCode("OCF_RUNNING_MASTER")
	if err != nil {
		return err
	}
	OCF_SUCCESS, err = importOcfExitCode("OCF_SUCCESS")
	if err != nil {
		return err
	}
	return nil
}
func importOcfExitCode(name string) (OcfExitCode, error) {
	stringValue := os.Getenv(name)
	intValue, err := strconv.Atoi(stringValue)
	if err != nil {
		return 0, fmt.Errorf("%s is set to an invalid value [%s]", name, stringValue)
	}
	return OcfExitCode(intValue), nil
}
func Diagnose(diagnostics Diagnostics) error {
	if !diagnostics.System {
		return &ServerUnhealthyError{RawValue: ServerCriticalError, Inner: fmt.Errorf("sp_server_diagnostics result indicates system error")}
	}
	if !diagnostics.Resource {
		return &ServerUnhealthyError{RawValue: ServerModerateError, Inner: fmt.Errorf("sp_server_diagnostics result indicates resource error")}
	}
	if !diagnostics.QueryProcessing {
		return &ServerUnhealthyError{RawValue: ServerAnyQualifiedError, Inner: fmt.Errorf("sp_server_diagnostics result indicates query processing error")}
	}
	return nil
}
func Exit(logger *log.Logger, exitCode int, err error) error {
	if err != nil {
		for _, line := range strings.Split(err.Error(), "\n") {
			logger.Println(line)
		}
	}
	os.Exit(exitCode)
	return nil
}
func GetLocalServerName(db *sql.DB) (serverName string, err error) {
	err = db.QueryRow("SELECT @@SERVERNAME").Scan(&serverName)
	return
}
func OcfExit(logger *log.Logger, ocfExitCode OcfExitCode, err error) error {
	return Exit(logger, int(ocfExitCode)+10, err)
}
func OpenDB(hostname string, port uint64, username string, password string, applicationName string, connectionTimeout time.Duration) (*sql.DB, error) {
	query := url.Values{}
	query.Add("app name", applicationName)
	query.Add("connection timeout", fmt.Sprintf("%d", connectionTimeout/time.Second))
	u := &url.URL{
		Scheme:   "sqlserver",
		User:     url.UserPassword(username, password),
		Host:     fmt.Sprintf("%s:%d", hostname, port),
		RawQuery: query.Encode(),
	}
	connectionString := u.String()
	db, err := sql.Open("mssql", connectionString)
	if err != nil {
		return nil, &ServerUnhealthyError{RawValue: ServerDownOrUnresponsive, Inner: err}
	}
	err = db.Ping()
	if err != nil {
		_ = db.Close()
		return nil, &ServerUnhealthyError{RawValue: ServerDownOrUnresponsive, Inner: err}
	}
	return db, nil
}
func OpenDBWithHealthCheck(
	hostname string, port uint64,
	username string, password string,
	applicationName string,
	connectionTimeout time.Duration,
	stdout *log.Logger) (db *sql.DB, err error) {
	dbChannel := make(chan *sql.DB)
	errChannel := make(chan error)
	timeoutChannel := time.After(connectionTimeout)
	go func() {
		var db *sql.DB
		var err error
		for i := uint(1); ; i++ {
			stdout.Printf("Attempt %d to connect to the instance at %s:%d and run sp_server_diagnostics\n", i, hostname, port)
			if db != nil {
				_ = db.Close()
			}
			db, err = OpenDB(hostname, port, username, password, applicationName, connectionTimeout)
			if err == nil {
				stdout.Printf("Connected to the instance at %s:%d\n", hostname, port)
				dbChannel <- db
				return
			}
			stdout.Printf("Attempt %d returned error: %s\n", i, err)
			errChannel <- err
			time.Sleep(1 * time.Second)
		}
	}()
	for {
		select {
		case db = <-dbChannel:
			var diagnostics Diagnostics
			diagnostics, err = QueryDiagnostics(db)
			if err != nil {
				_ = db.Close()
				return nil, err
			}
			err = Diagnose(diagnostics)
			return
		case err = <-errChannel:
		case _ = <-timeoutChannel:
			if err == nil {
				err = &ServerUnhealthyError{
					RawValue: ServerDownOrUnresponsive,
					Inner:    fmt.Errorf("timed out while attempting to connect to the instance at %s:%d and run sp_server_diagnostics", hostname, port),
				}
			}
			return
		}
	}
}
func QueryDiagnostics(db *sql.DB) (result Diagnostics, err error) {
	rows, err := db.Query("EXEC sp_server_diagnostics")
	if err != nil {
		return result, err
	}
	defer rows.Close()
	for rows.Next() {
		var creationTime, componentType, componentName, stateDesc, data string
		var state int  
		err = rows.Scan(&creationTime, &componentType, &componentName, &state, &stateDesc, &data)
		if err != nil {
			break
		}
		switch componentName {
		case "system":
			result.System = state == 1
		case "resource":
			result.Resource = state == 1
		case "query_processing":
			result.QueryProcessing = state == 1
		}
	}
	err = rows.Err()
	return
}
func ReadCredentialsFile(filename string) (username string, password string, err error) {
	file, err := os.Open(filename)
	if err != nil {
		return
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	if !scanner.Scan() {
		err = fmt.Errorf("Could not read first line to extract username.")
		return
	}
	username = scanner.Text()
	if !scanner.Scan() {
		err = fmt.Errorf("Could not read second line to extract password.")
		return
	}
	password = scanner.Text()
	return
}