DECLARE @errCode INT = 0
			
--Update ClientId in SMControlHost and SMArray Tables based on SMHostAlias
UPDATE SMControlHost 
SET ClientId = client.id
FROM SMControlHost AS ctrlHost
	INNER JOIN SMHostAlias AS alias
		ON ctrlHost.ClientId = 1
		AND alias.RefType = 5 
		AND ctrlHost.ControlHostId = alias.RefId
	INNER JOIN APP_Client AS client
		ON (alias.AliasName = client.name OR alias.AliasName = client.net_hostname)

SET	@errCode	= @@ERROR
IF	@errCode != 0 GOTO CX_EXIT 

--MR: 317199 Update the SMArray table only when the ArrayID,ClientID combination is not already present
UPDATE array1
SET ClientId = ctrlHost.ClientId
FROM SMControlHost AS ctrlHost
    INNER JOIN SMArray AS array1
        ON array1.ClientId = 1
        AND array1.ArrayName = ctrlHost.SMArrayId
	LEFT OUTER JOIN SMArray AS array2 
		ON ctrlHost.SMArrayId = array2.ArrayName
		AND ctrlHost.clientId = array2.ClientId
		WHERE array2.clientId IS NULL
		
SET	@errCode	= @@ERROR
IF	@errCode != 0 GOTO CX_EXIT 

CX_EXIT:

IF @errCode != 0
	SELECT 2
ELSE
	SELECT 0

RETURN

