I'm using SQL Server as a warehouse to analyze log files. Those log files carry a kind of bussiness hierarchy (worker in this example):

```
Log Entry Id, Log Message
1           , Start Worker
2           , Do Cool Stuff
3           , Start Worker
4           , Do further cool stuff
5           , Start Worker
6           , This is a lot of working
7           , End worker
8           , End worker
9           , End worker

```

I need to relate the log entries to the current worker. The rule is quite simple: once a "Start worker" message is found, assign all following log entries to this worker. In the example hierarchy this means:

```
Log Entry Id, Log Message              , Worker
1           , Start Worker             , 1 (we take the entry id as worker id)
2           , Do Cool Stuff            , 1
3           , Start Worker             , 3
4           , Do further cool stuff    , 3
5           , Start Worker             , 5
6           , This is a lot of working , 5
7           , End worker               , 5
8           , End worker               , 3
9           , End worker               , 1

```

Currently I'm using a stored procedure iterating all log entries with a cursor which basically uses a stack to establish the relationship between log entries and workers:

```
CREATE PROCEDURE CalculateRelations
AS
BEGIN
    DECLARE entries_cur CURSOR FOR
    SELECT Id, LogMessage
    FROM LogEntries
    ORDER BY Id;

    DECLARE @Id BIGINT;
    DECLARE @LogMessage VARCHAR(128);
    DECLARE @ParentWorker BIGINT;
    DECLARE @WorkerStack VARCHAR(MAX) = '';

    OPEN entries_cur;
    FETCH NEXT FROM entries_cur INTO @Id, @LogMessage;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        EXEC dbo.GetParentWorker @WorkerStack OUT, @Id, @LogMessage, @ParentWorker OUT;

        UPDATE LogEntries
        SET ParentWorker = @ParentWorker
        WHERE Id = @Id;

        FETCH NEXT FROM entries_cur INTO @Id, @LogMessage;
    END;

    CLOSE entries_cur;
    DEALLOCATE entries_cur;
END;
GO

```

`GetParentWorker` is a stored procedure which uses the given `VARCHAR` variable `WorkerStack` as a stack. This means

* "Start worker" message leads to adding (push) the `Id` to that `VARCHAR`
* "End worker" message leads to removing and returning (pop) the last `Id` from that `VARCHAR`
* all other messages lead to just returning (read) the last `Id` from that `VARCHAR` without modifying it

Now I'm wondering if it's possible to replace this cursor construct by a `UPDATE` statement. I'm not that deep in SQL and SQL Server, but might it be possible to realize this by dynamic variable assignment, `CASE` and the usage of the return value of `GetParentWorker`?