日期:2014-05-16  浏览次数:20630 次

把CASE...When...Then放在循环里面的语句实现
刚开始接触SQL,新人一个,希望大家能指点指点,谢啦

环境:Microsoft SQL Server 2012

数据由五列组成,分别是 type_id, start_time, end_time, int_value, bool_value

表如下:



要求出在 type_id同时等于10和 2, int_value同时等于(1或2或4)和 128 时的时间总和

想法是要在要在循环里面加入条件语句,用循环的变量来指定需要查询的时间段,然后制作用bool_value表示二进制的表格,然后相加bool_value等于1的所有时间

写了如下的句子,一直到制作bool_value表格,还没相加


declare @t int, @int1 int, @int2 int
select @int1 = (select int_value from [dbo].[OEE] where mach_id=9001 and type_id=2 and start_time=@t and end_time=(@t+1))
select @int2 = (select int_value from [dbo].[OEE] where mach_id=9001 and type_id=10 and start_time=@t and end_time=(@t+1))
set @t=1286888400
while @t< 1286913601
begin
select 
case  
when @int1=128 and @int2 in (1,2,4)
then insert into [dbo].[OEE] (type_id, bool_value) values (111, 1)
else
insert into [dbo].[OEE] (type_id, bool_value) values (111, 0)
set @t=@t+1
end


但是现在总是显示insert和else这里有错误
是then语句后面不能加入SQL语句还是怎么样呢?
是我的循环写错了吗?@t能用到最开始对变量赋值的语句中不?那么会不会根据循环一直往上+1的改变呢?

谢谢大家的帮忙
------解决方案--------------------
DECLARE @t        INT,
        @int1     INT,
        @int2     INT

SET @t = 1286888400
WHILE @t < 1286913601
BEGIN
    SELECT @int1 = int_value
    FROM   [dbo].[OEE]
    WHERE  mach_id            = 9001
           AND TYPE_ID        = 2
           AND start_time     = @t
           AND end_time       = (@t + 1)
    
    SELECT @int2 = int_value
    FROM   [dbo].[OEE]
    WHERE  mach_id            = 9001
           AND TYPE_ID        = 10
           AND start_time     = @t
           AND end_time       = (@t + 1)
    
    IF @int1 = 128
       AND @int2 IN (1, 2, 4)
        INSERT INTO [dbo].[OEE]
          (
            TYPE_ID,