Question

I am honestly having trouble articulating this question to my co-workers, so please go easy on me. I can elaborate if needed.

So here is the deal, I have a theoretical question about SQL's Case When statement. This isn't a specific situation that I need help with, it is just a complex question I need answered about the abilities of the T-SQL language, which I want to know for my own future purposes.

I know that in Java you can creat loops and use the .hasNext() method to continuosly retrieve input from a source (the keyboard for example), and by doing this you can essentially create a loop that does [some action] until you run out of input.

I would like to know if I can use a similar sort of function (correct me if function is not the right terminology) that I can use along with a Case When statement in T-SQL.

Here is some psuedo code for example:

case when [Column Y has next] then 'X'

Essentially I want to know if I can tell a Case When funciton to execute continuosly until it runs out of values or encounters a null value.

Please let me know if I am on the right track here, my brain is kind of stuck somewhere between the object oriented world of Java and the relational DB world of SQL. All feedback is appreciated.

Was it helpful?

Solution

Case-When is basically a row operation. Specifically, you need to think about the set of data you are working with based on joins and where clauses, and then think about the case-when operator running against each row in the result set. Because of this, there is no concept of previous row, next row or "has next".

That being said, there's always a way to accomplish what you want. Generically speaking, I would usually recommend a "self join". This is really just a special case of a regular type of join (inner, left, right, full and cross). The difference here is that instead of joining two different tables, you join the same table back to itself. If you introduce a Row_Number function and include that in the where clause, you can effectively join one row to the next row, which would effectively give you a way to accomplish a "has next" functionality.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top