  /*This script will update all the email and notification frequencies for all users on a specific portal. Written by Tony Lee*/
  DECLARE @PortalID AS INT = 0 /*Set PortalID*/
  DECLARE @UserID AS INT
  DECLARE @MessagesEmailFrequency AS INT = 0 /*Set Frequency*/
  DECLARE @NotificationsEmailFrequency AS INT = 0 /*Set Frequency*/
  
  DECLARE @EmailCursor AS CURSOR;

	SET @EmailCursor = CURSOR FOR
		SELECT [UserID]  
		FROM UserPortals
		WHERE PortalID = 0; /*Set PortalID*/

	OPEN @EmailCursor;
  
	FETCH NEXT FROM @EmailCursor INTO @UserID;
  
	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF NOT EXISTS (SELECT * FROM [CoreMessaging_UserPreferences] WHERE UserId = @UserID and PortalId = @PortalID)
			BEGIN
				   INSERT INTO [dbo].[CoreMessaging_UserPreferences]
								   ([PortalId]
									,[UserId]
									,[MessagesEmailFrequency]
									,[NotificationsEmailFrequency])
							 VALUES
								   (@PortalID
								   ,@UserID
								   ,@MessagesEmailFrequency
								   ,@NotificationsEmailFrequency)
			END
		ELSE
			BEGIN
				UPDATE [CoreMessaging_UserPreferences] 
				SET MessagesEmailFrequency = @MessagesEmailFrequency
				, [NotificationsEmailFrequency] = @NotificationsEmailFrequency 
				WHERE [UserId] = @UserID AND [PortalId] = @PortalID
			END
				
		FETCH NEXT FROM @EmailCursor INTO @UserID;
	END

CLOSE @EmailCursor;

DEALLOCATE @EmailCursor;