-1

I work for writing reporting with SQL. But unfortunately, queries are very complicated. I analyzed this issue like following:

  • There is a VIEW and some columns to show customers
  • There are some columns have many conditional clauses (ex. if...else...)
  • These conditional clauses depends on JOINed tables
  • As a result, the VIEW has eight or more quadrants

EDIT1(Work in progress)

Model of source data side (not reporting).

enter image description here

Is there any good way to expel logics from SQL ? Any another solutions are welcome.

3
  • Create a compact, but adequate, model of your system and add it to your question.
    – Akina
    Commented Aug 7, 2018 at 8:15
  • Okay, I'll do it
    – hiropon
    Commented Aug 7, 2018 at 10:23
  • It's 2 weeks later, and still no model.
    – Rick James
    Commented Aug 22, 2018 at 3:44

2 Answers 2

0

The answer can only be as precise as the question. I remember the words of Joe Celko: "if you're in the habit of writing complex SQL statements, you probably have a faulty datamodel". Improve the match between the model and the SQL and the SQLstatements will simplify

0

Without having seen the code:

Sometimes IF clauses can be refactored using the CASE function. The CASE function can be used for a specific column. If the only difference between two queries used in an IF clause, the CASE function can be used to specify conditions within a single query.

You can also split the query into many parts, for example by using temporary tables.

If the query can be executed differently dependent on the values, you can also specify the query OPTION (RECOMPILE) in some cases to recompile the execution plan with each run in order to increase performance. This is mainly relevant if you only need to lookup the join conditions in some cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.