I have table like below, where status =0 means active and 2 bottom records merged with top one.
Now I need all the consolidatedDescription in active Description like below:
how do i use Cursor ..?
The short answer to the question "how do I use Cursor?" is DON'T, just don't. There is no reason whatsoever to consider using a cursor for something like this. One of the reasons to consider using a cursor is when there is a scenario where you need to, say, execute somewhat complex stored procedure for each row in your table, and that stored procedure expects some parameters gathered from the column values of the row. In most other scenarios, the knee jerk reaction to wheel out a cursor simply hints the lack of knowledge of the basic T-SQL functionality.
In this specific case, it looks like you have a scenario when the row may have NULL value in the MasterID column which probably means that there might be other rows in this table which have their respective MasterID equal to the ID value of that row where MasterID is null. This makes the data look like a hierarchy designed as adjacency list which is only 2 levels deep at most. If this assumption is incorrect then please update your question. For example, if there is a possibility that some rows with NOT NULL values in the MasterID column have some other rows which have their MasterID equal to the ID of such row then the solution will be different (to accommodate the hierarchy with whatever number of levels).
Based on the sample data in question, the following query will produce desired result:
Hope this helps.
answered Jan 11 at 05:36 PM