Skip to content
Advertisement

SQL – How to call a part of query conditionally

I need to write a SQL query like this:

do step1

do step2

do step3 – this step does a lot of stuffs: define variables, use some variables defined in step 1, query a lot of data into temporary table…

How to make step 3 a reusable query to avoid calling step 3 unnecessarily? notice that step 3 should be a part of the whole query

When I try to create a @step3Query NVARCHAR(MAX), SET @step3Query = ‘…’ Then call this query in appropriated places by call “EXEC sp_executesql @step3Query”. But I got a lot of errors, and I am not sure that is a correct way to do task like that. Any suggestions would be highly appreciated.

Advertisement

Answer

Here is one method that could work (depending on your exact circumstance). The main thing for this is that it’s easy, as well as easy to read.

You could have 3 variables to use as flags e.g., @Query3_Flag, @Query4_flag, @Query5_flag.

Your conditional checks just set these flags e.g.,

Before each of queries 3, 4 and 5, have the IF statement check the flag and only run the query if the flag is set to 1 e.g.,

Note that the queries will need to be in the correct order.

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