DECLARE @EntityIdString VARCHAR(max)

SELECT @EntityIdString = COALESCE(@EntityIdString + ', ', '') + CAST(entityid AS VARCHAR(10))
FROM tbentity
WHERE entityTypeId = 4
	AND STATUS = 'open'
	AND Entity LIKE '%inform%'

DECLARE @EntityId BIGINT

DECLARE cur CURSOR
FOR
SELECT value
FROM dbo.fn_Split(@EntityIdString, ',')

OPEN cur

FETCH NEXT
FROM cur
INTO @EntityId

WHILE @@FETCH_STATUS = 0
BEGIN
	IF EXISTS (
			SELECT *
			FROM tbEntity WITH (NOLOCK)
			WHERE EntityID = @EntityId
			)
	BEGIN
		DECLARE @TransactionControlInfoId BIGINT

		SELECT @TransactionControlInfoId = TransactionControlInfoId
		FROM tbTransactionControlInfo WITH (NOLOCK)
		WHERE ControlInfoID = 150
			AND EntityID = @EntityId
			AND BusinessDay = '2020-1-15'
			AND SystemTransactionID IS NULL

		DELETE
		FROM tbTransactionControlInfo
		WHERE TransactionControlInfoId = @TransactionControlInfoId

		DELETE
		FROM tbCustomerOnAccountBalanceEvent
		WHERE TransactionControlInfoId IN (
				SELECT TransactionControlInfoId
				FROM tbTransactionControlInfo
				WHERE ControlInfoID = 138
					AND EntityID = @EntityId
					AND BusinessDay = '2020-1-15'
				)
	END

	FETCH NEXT
	FROM cur
	INTO @EntityId
END

CLOSE cur

DEALLOCATE cur
