重复条件阻止SQL

时间:2016-12-02 06:03:38

标签: sql loops if-statement for-loop

  

我想按照以下条件创建一个重复的IF ELSE或FOR LOOP条件块

     

我在数据表中有一个“创建日期”列

我想实现以下条件

0-5 days from created date  
print text1  
6-10 from created date   
print text2  
11-15   
print text3  
16-20   
print text4  
21-25  
print text1  
26-30  
print text2  
  

等等。
  因此,在20天之后,第一个文本会再次打印,并且每隔5天就会显示4个文本。

2 个答案:

答案 0 :(得分:1)

在SQL Server中,您可以使用CASE WHEN

SELECT name, total, 
CASE  
 WHEN datediff(day, createdDate, getdate()) <5 THEN 'Almost Due'
 WHEN datediff(day, createdDate, getdate()) BETWEEN 6 AND 10  THEN 'Due Now'
   ...
 WHEN datediff(day, createdDate, getdate()) >20 THEN 'PAY NOW!!'
END as discount from invoice

或在您复杂的问题

SELECT name, total, 
CASE  (datediff(day, createdDate, getdate()) % 25)
 WHEN  <5 THEN 'Almost Due'
 WHEN  BETWEEN 6 AND 10  THEN 'Due Now'
   ...
 WHEN  >20 THEN 'PAY NOW!!'
END as discount from invoice

答案 1 :(得分:0)

使用整数除法和模数的组合,确切的运算符取决于您的SQL方言。以下是T-SQL,MySQL将使用DIV而不是\

CASE (DATEDIFF(DAY, CreatedDate, GetDate()) \ 5) % 4
  WHEN 0 THEN 'text1'
  WHEN 1 THEN 'text2'
  WHEN 2 THEN 'text3'
  WHEN 3 THEN 'text4' END