游标在结果中不包含第一个select语句

时间:2018-12-30 10:17:18

标签: sql cursor

我有以下代码。本来希望看到三个表,用于每个选择语句,但是由于某些原因,第一个选择语句的表未包含在结果中。

declare @Charge dec(10,2)
DECLARE CRS CURSOR
FOR 

SELECT 0.01*v9.charge  AS firstTENDAYS
from v9
where datepart(day,v9.trans_time_date) between 0 and 10  and 
@Charge=v9.charge


SELECT 0.02*V9.charge  AS secondTENDAYS
 from v9
where datepart(day,v9.trans_time_date) between 11 and 20  and
@Charge=v9.Charge

SELECT 0.03*V9.charge  AS thirdTENDAYS
from v9
where datepart(day,v9.trans_time_date) between 21 and 31  and
@Charge=v9.Charge

open CRS
FETCH NEXT FROM CRS
INTO @Charge
print  

WHILE @@FETCH_STATUS=0
BEGIN
print @Charge 
FETCH NEXT FROM CRS
INTO @Charge

END
CLOSE CRS
DEALLOCATE CRS

2 个答案:

答案 0 :(得分:0)

您的查询让我感到困惑。首先,我不明白为什么您要使用游标而不是select设置值。

但是,您的查询不应返回任何内容。考虑:

select 0.01*v9.charge  AS firstTENDAYS
from v9
where datepart(day, 9.trans_time_date) between 0 and 10 and
       @Charge = v9.charge;
声明了

@Charge,但未指定任何值,因此它是NULL。那应该无法进行任何比较。

您的三个查询之间没有任何联系,因此光标只是第一个查询。这可能与您看到的问题有关。

我怀疑您想要一个更简单的查询,例如:

select (case when day(v9.trans_time_date) <= 10 then 'firstTenDays'
             when day(v9.trans_time_date) <= 20 then 'secondTenDays'
             else 'thirdTenDays'
        end) as which,
       (case when day(v9.trans_time_date) <= 10 then 0.01 * v9.charge
             when day(v9.trans_time_date) <= 20 then 0.02 * v9.charge
             else 0.03 * v9.charge
        end) as chart
from v9;

答案 1 :(得分:0)

这绝对不应该用游标来完成,而要使用常规选择。 但是只是为了向您展示光标的工作方式,我将其放在此处:

Declare @firstTENDAYS table (charge decimal)
Declare @secondTENDAYS table (charge decimal)
Declare @thirdTENDAYS table (charge decimal)

Declare @Charge dec(10,2) =10
Declare CRS CURSOR FOR Select v9.charge, v9.trans_time_date From v9
Declare @v9_Charge numeric
Declare @v9_InsertDate smalldatetime


Open CRS
FETCH NEXT FROM CRS INTO @v9_Charge, @v9_InsertDate 
WHILE @@FETCH_STATUS=0
BEGIN
 If @v9_Charge = @Charge
 Begin
        If @v9_InsertDate  between 0 and 10   
         Insert Into @firstTENDAYS SELECT 0.01*@v9_Charge  
        Else If  @v9_InsertDate  between 10 and 20   
         Insert Into @secondTENDAYS SELECT 0.02*@v9_Charge  
        Else If  @v9_InsertDate  between 21 and 31  
         Insert Into @thirdTENDAYS SELECT 0.03*@v9_Charge 
 End

FETCH NEXT FROM CRS INTO @v9_Charge, @v9_InsertDate 
END;
CLOSE CRS;
DEALLOCATE CRS;


select * from  @firstTENDAYS
select * from  @secondTENDAYS 
select * from  @thirdTENDAYS