Skip to content
Advertisement

Is there a way to dynamically execute queries in SQL without using user defined function?

I am currently working on the table containing some documents data, focusing on the columns containing date of document and net income. What I have to do is to write an sql statement which will result in a table showing the summary of each year’s net income divided into months, like this:

To solve this, I created a following function:

and executed query like that:

This results in the expected table. BUT The problem is, my boss would like me to not use any functions for some reason. I can declare variables, tho. So my question is, is there a way to solve this without using a function? A while loop maybe? I know I could make a select command for each month and then join them together but I am looking for a more sophisticated solution than eleven joins… Any idea? 🙂

Advertisement

Answer

No need for this convoluted logic involving the function. As I understand your problem statement, you can get the result that you want in a single query, using conditional aggregation:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement