简体   繁体   English

SQL - 如何有条件地调用查询的一部分

[英]SQL - How to call a part of query conditionally

I need to write a SQL query like this:我需要编写这样的 SQL 查询:

do step1做第一步

do step2做第2步

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...做第3步——这一步做了很多事情:定义变量,使用第1步中定义的一些变量,将大量数据查询到临时表中......

if(cond1)

   if(cond2)        
 
       Begin            
          do step 4             
          call step 3 here      
       End  
    else
    
      Begin             
           do step 5        
      End  
  else  
 
  Begin         
     call step 3 here   
  End

How to make step 3 a reusable query to avoid calling step 3 unnecessarily?如何使第 3 步成为可重复使用的查询以避免不必要地调用第 3 步? notice that step 3 should be a part of the whole query请注意,第 3 步应该是整个查询的一部分

When I try to create a @step3Query NVARCHAR(MAX), SET @step3Query = '...' Then call this query in appropriated places by call "EXEC sp_executesql @step3Query".当我尝试创建 @step3Query NVARCHAR(MAX), SET @step3Query = '...' 然后通过调用“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.任何建议将不胜感激。

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 eg, @Query3_Flag, @Query4_flag, @Query5_flag.您可以将 3 个变量用作标志,例如@Query3_Flag、@Query4_flag、@Query5_flag。

Your conditional checks just set these flags eg,您的条件检查只是设置这些标志,例如,

IF (condition1)
    BEGIN
    SET @Query4_Flag = 1;
    SET @Query3_flag = 1;
    SET @Query5_flag = 0;
    END

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 eg,在每个查询 3、4 和 5 之前,让 IF 语句检查标志,并且仅在标志设置为 1 时才运行查询,例如,

IF @Query3_Flag = 1 
    BEGIN
    (run Query 3)
    END

Note that the queries will need to be in the correct order.请注意,查询需要按正确的顺序排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM