SELECT
	'INSERT INTO [dbo].[OrgRole] ([IpOrg],[RoleCode],[MandatoryFlag],[DefaultFlag],[GuestFlag],[IpOwner]) SELECT '
		+ CONVERT(VARCHAR,[IpOrg]) + ','
		+ '''' + [RoleCode] + ''','
		+ CONVERT(VARCHAR, [MandatoryFlag]) + ','
		+ CONVERT(VARCHAR, [DefaultFlag]) + ','
		+ CONVERT(VARCHAR, [GuestFlag]) + ','
		+ CONVERT(VARCHAR, [IpOwner])
			+ ' WHERE NOT EXISTS (SELECT 1 FROM [dbo].[OrgRole]'
				+ ' WHERE [IpOrg] = ' + CONVERT(VARCHAR,[IpOrg])
				+ ' AND [RoleCode] = ''' + [RoleCode] + ''');' AS INSERT_SQL,
	'UPDATE [dbo].[OrgRole] SET '
		+ '[MandatoryFlag] = ' + CONVERT(VARCHAR,[MandatoryFlag]) + ','
		+ '[DefaultFlag] = ' + CONVERT(VARCHAR, [DefaultFlag]) + ','
		+ '[GuestFlag] = ' + CONVERT(VARCHAR, [GuestFlag]) + ','
		+ '[IpOwner] = ' + CONVERT(VARCHAR, [IpOwner])
			+ ' WHERE [IpOrg] = ' + CONVERT(VARCHAR,[IpOrg])
			+ ' AND [RoleCode] = ''' + [RoleCode] + ''';' AS UPDATE_SQL,
	'UPDATE [dbo].[OrgRole] SET '
		+ '[MandatoryFlag] = ' + CONVERT(VARCHAR,[MandatoryFlag]) + ','
		+ '[DefaultFlag] = 0,'
		+ '[GuestFlag] = ' + CONVERT(VARCHAR, [GuestFlag]) + ','
		+ '[IpOwner] = ' + CONVERT(VARCHAR, [IpOwner])
			+ ' WHERE [IpOrg] = ' + CONVERT(VARCHAR,[IpOrg])
			+ ' AND [RoleCode] = ''YFREPORTCONSUMER'';' AS UPDATE_YFREPORTCONSUMER_SQL,
	[IpOrg],
	[RoleCode],
	[MandatoryFlag],
	[DefaultFlag],
	[GuestFlag],
	[IpOwner]
FROM
	[dbo].[OrgRole]
WHERE
	[RoleCode] IN ('REPORTCONSUMEREXTERNAL','REPORTCONSUMERINTERNAL','SERVICEDESK')