USE ArizonaREP

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'address' AND TABLE_SCHEMA='dbo' AND COLUMN_NAME = 'phcy_ou_code')
BEGIN
	ALTER TABLE dbo.address ADD phcy_ou_code VARCHAR(15) NULL;
END 

UPDATE a SET phcy_ou_code = ou.OU_code
FROM dbo.Address a
    JOIN [dbo].[Address_OU_link] l ON l.AOUL_address = a.Address_GUID
    JOIN dbo.Organizational_unit ou ON ou.Organizational_unit_GUID = COALESCE(a.AD_update_OU, a.AD_creation_OU)
WHERE a.phcy_ou_code IS NULL 

IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'address' AND TABLE_SCHEMA='dbo' AND COLUMN_NAME = 'phcy_ou_code')
BEGIN
	ALTER TABLE dbo.address DROP COLUMN phcy_ou_code;
END 
