Mudassir Hasan
Mudassir Hasan

Reputation: 28751

IF..ELSE block not working SQL

I have a if else block in my procedure . The value of a temporary variable @timeID is set in this block according to today's date.

declare @timeId int
if(datename(Dw,getdate())='Sunday' or datename(Dw,getdate())='Saturday')
begin
  set @timeId=2
end

if(datename(Dw,getdate())!='Sunday' or datename(Dw,getdate())!='Saturday')
begin
 if(convert(varchar(11),getdate(),108)<='08:30:00')
  begin
   set @timeId=0
  end
 else
  begin
   set @timeId=1
  end
end


select @timeId as TimeID

Since today is Saturday , @timeID must be set equal to 2. But output shows @timeId=1 which results in wrong result from my procedure. Please help what's wrong.

select datename(Dw,getdate())

returns Saturday

Upvotes: 3

Views: 1739

Answers (2)

ExactaBox
ExactaBox

Reputation: 3395

Your second if clause should use AND, not OR. Every day is NOT Sunday OR NOT Saturday

Upvotes: 3

Mitch Wheat
Mitch Wheat

Reputation: 300559

OK, assume it is Saturday:

The first IF block runs.

Then the second IF block runs because of the OR condition on != Sunday, overwriting @timeid.

You want an ELSE (and in fact, you can drop the extra test, simplifying the code):

declare @timeId int
if(datename(Dw,getdate())='Sunday' or datename(Dw,getdate())='Saturday')
begin
  set @timeId=2
end

ELSE

begin
 if(convert(varchar(11),getdate(),108)<='08:30:00')
  begin
   set @timeId=0
  end
 else
  begin
   set @timeId=1
  end
end

Upvotes: 4

Related Questions