CREATE PROC [dbo].[@PROCNAME@] 
AS
SET ANSI_NULLS ON
SET ANSI_WARNINGS ON
SET NOCOUNT ON

BEGIN
	DECLARE @RPMSyncTable VARCHAR(30), @RPMSyncKey VARCHAR(30), @RPMSyncValue NVARCHAR(255)
	DECLARE @CompanyID VARCHAR(100), @Result INT
	
	/* Get Company ID GUID from the Company Settings table */
	SELECT @CompanyID = LTRIM(RTRIM(RPM_Company_Setting_Valu))
	FROM @COMPANYSETUPTABLE@
	WHERE RPM_Company_Setting_Key = '@COMPANYIDSETTING@' AND INTERID = DB_NAME() 
	
	DECLARE RPM_cursor CURSOR FOR
		SELECT	LTRIM(RTRIM(RPM_Sync_Table_Name)),
				LTRIM(RTRIM(RPM_Sync_Key_Field_Name)),
				LTRIM(RTRIM(RPM_Sync_Key_Field_Value))
			FROM @SYNCQUEUETABLE@

	OPEN RPM_cursor
	FETCH NEXT FROM TR_cursor INTO @RPMSyncTable, @RPMSyncKey, @RPMSyncValue
	WHILE (@@FETCH_STATUS = 0) 
	BEGIN 
		/* Call the REST service to add this to the Data Sync Queue in RPM */
		EXEC @SYSTEMDATABASE@.dbo.usp_RPMSyncQueue @CompanyID
			,@RPMSyncTable
			,@RPMSyncKey
			,@RPMSyncValue
			,@Result OUTPUT 
	
		/* Delete queued record if the stored procedure returned 0;   */ 
		/* Otherwise, leave it in the queue for the next time around. */
		IF @Result = 0
		BEGIN
			DELETE @SYNCQUEUETABLE@
			WHERE RPM_Sync_Table_Name = @RPMSyncTable AND RPM_Sync_Key_Field_Value = @RPMSyncValue;
		END

		FETCH NEXT FROM RPM_cursor INTO @RPMSyncTable, @RPMSyncKey, @RPMSyncValue
	END  

	CLOSE RPM_cursor  
	DEALLOCATE RPM_cursor 
END