日期:2014-05-18  浏览次数:20646 次

SQL2008中条件语句的问题
写了一个条件语句,请看源码:
SQL code

--创建timesutc表
IF OBJECT_ID('timesutc') IS NOT NULL
DROP TABLE timesutc;
GO
CREATE TABLE timesutc
(id INT IDENTITY(1,1),
 time1 DATETIME NULL,
 timesutc BIGINT NULL );
--创建条件插入语句
declare @datetime INT,
        @dw INT,
        @dt DATETIME,
        @dt2 DATETIME;
        --@timesty AS timesutctype;
SET @dt='2012-07-05'; 
SET @dt2=DATEADD(dy,1,@dt);
WHILE @dt2<='2012-07-26'
  BEGIN
    SET @dw=DATEPART(dw,@dt2);
    IF @dw<>1 OR @dw<>7
      BEGIN
        set @datetime=DATEDIFF(ss,'1970-01-01 00:00:00',@dt2);
          INSERT INTO timesutc VALUES (@dt2,@datetime);
      END;           
      SET @dt2=DATEADD(dy,1,@dt2);
  END;


这个代码中IF条件我是将周末过滤掉,不等于1(1表示星期天)或7(7表示星期六)时才插入表,但结果等于1或7时都插入到表中了,这是为什么啊?是我语句写的不对吗,请高手赐教,谢谢!

------解决方案--------------------
SQL code

IF OBJECT_ID('timesutc') IS NOT NULL
DROP TABLE timesutc;
GO
CREATE TABLE timesutc
(id INT IDENTITY(1,1),
 time1 DATETIME NULL,
 timesutc BIGINT NULL 
 );
declare @dt DATETIME,@dt2 DATETIME;
        --@timesty AS timesutctype;
SET @dt='2012-07-05'; 
select @dt2=DATEADD(DD,1,@dt)
while @dt2<='2012-07-26'
begin
  if DATEPART(W,@dt2)=1 or  DATEPART(W,@dt2)=7
  begin
    set @dt2=DATEADD(DD,1,@dt2)
  end
  else
  begin
    insert timesutc
    select @dt2,DATEDIFF(SS,'1970-01-01 00:00:00',@dt2)
    set @dt2=DATEADD(DD,1,@dt2)      
  end
end

select * from timesutc
/*
id    time1    timesutc
1    2012-07-06 00:00:00.000    1341532800
2    2012-07-09 00:00:00.000    1341792000
3    2012-07-10 00:00:00.000    1341878400
4    2012-07-11 00:00:00.000    1341964800
5    2012-07-12 00:00:00.000    1342051200
6    2012-07-13 00:00:00.000    1342137600
7    2012-07-16 00:00:00.000    1342396800
8    2012-07-17 00:00:00.000    1342483200
9    2012-07-18 00:00:00.000    1342569600
10    2012-07-19 00:00:00.000    1342656000
11    2012-07-20 00:00:00.000    1342742400
12    2012-07-23 00:00:00.000    1343001600
13    2012-07-24 00:00:00.000    1343088000
14    2012-07-25 00:00:00.000    1343174400
15    2012-07-26 00:00:00.000    1343260800
*/

------解决方案--------------------
SQL code

IF @dw<>1 AND @dw<>7