USE IBADosCompassDB
GO

DECLARE @myloginname varchar(50)
SELECT @myloginname=name FROM sys.server_principals WHERE sid=0x010100000000000512000000
EXEC dbo.sp_changedbowner @loginame=@myloginname

IF (SELECT count(*) FROM db_version_info WHERE curr_version = N'V06') = 1
BEGIN
    UPDATE db_version_info SET curr_version = 'V07', min_version = 'V07', applied = GETDATE() WHERE curr_version = N'V06'
END

USE IBADosCompassConfig
GO

DECLARE @myloginname varchar(50)
SELECT @myloginname=name FROM sys.server_principals WHERE sid=0x010100000000000512000000
EXEC dbo.sp_changedbowner @loginame=@myloginname

IF (SELECT count(*) FROM db_version_info WHERE curr_version = N'V03') = 1
BEGIN
    IF EXISTS (SELECT name FROM sys.server_principals WHERE name = N'iba_user')
      BEGIN
         PRINT 'Dropping login ' + N'iba_user';
         exec sp_droplogin [iba_user]
       END

    IF EXISTS (SELECT name FROM sys.server_principals WHERE name = N'iba_admin')
       BEGIN
         PRINT 'Dropping login ' + N'iba_admin';
         exec sp_droplogin [iba_admin]
       END

    UPDATE db_version_info SET curr_version = 'V04', applied = GETDATE() WHERE curr_version = N'V03'
END

USE [IBADosCompassDB]
GO
DECLARE @builtin_users nvarchar(128)
DECLARE @sqlString nvarchar(256)
SET @builtin_users=quotename((SELECT name  FROM sys.server_principals where sid=0x01020000000000052000000021020000))
SELECT @builtin_users

IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = @builtin_users)
BEGIN
	SET @sqlString =  'CREATE USER ' + @builtin_users +' FOR LOGIN ' + @builtin_users
	EXEC sp_executesql @sqlString;
END
SET @sqlString =  'sp_addrolemember db_datareader, ' + @builtin_users
EXEC sp_executesql @sqlString;
SET @sqlString =  'sp_addrolemember db_datawriter, ' + @builtin_users
EXEC sp_executesql @sqlString;


USE [IBADosCompassConfig]
GO
DECLARE @builtin_users nvarchar(128)
DECLARE @sqlString nvarchar(256)
SET @builtin_users=quotename((SELECT name  FROM sys.server_principals where sid=0x01020000000000052000000021020000))
SELECT @builtin_users

IF NOT EXISTS (SELECT name FROM sys.server_principals WHERE name = @builtin_users)
BEGIN
	SET @sqlString =  'CREATE USER ' + @builtin_users +' FOR LOGIN ' + @builtin_users
	EXEC sp_executesql @sqlString;
END
SET @sqlString =  'sp_addrolemember db_datareader, ' + @builtin_users
EXEC sp_executesql @sqlString;
SET @sqlString =  'sp_addrolemember db_datawriter, ' + @builtin_users
EXEC sp_executesql @sqlString;