Link to home
Start Free TrialLog in
Avatar of websss
websssFlag for Kenya

asked on

sql if statement always executing - help

Hi, i have this T SQL


declare @recount int
set @recount = 3
print @recount

if @recount < 1
Print 'sending email'
USE [msdb]
    EXEC msdb.dbo.sp_send_dbmail
      @profile_name = 'WltProfile',
      @recipients = 'me@domain.com',
      @subject = 'import exe may of has crashed on dev ',
      @body = 'This is an automatic email ...' 

Open in new window


It SHOULD ignore the IF and step over it
however, when i Run this, i get this in results pane:
3
Mail (Id: 1043) queued.

Open in new window



Its never printing the text 'sending email'
And its always sending the email even though it shouldn't execute that code as its inside the if

What is wrong with this code?
ASKER CERTIFIED SOLUTION
Avatar of Akilandeshwari N
Akilandeshwari N

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Guy Hengel [angelIII / a3]
I agree with above: BEGIN END is required here
note that the USE will not work (if I remember correctly), and should be avoided any now
declare @recount int
set @recount = 3
print @recount

IF @recount < 1
BEGIN
  Print 'sending email'

    EXEC msdb.dbo.sp_send_dbmail
      @profile_name = 'WltProfile',
      @recipients = 'me@domain.com',
      @subject = 'import exe may of has crashed on dev ',
      @body = 'This is an automatic email ...' 
END -- if @recount < 1

Open in new window

note that I do a comment on the END to inform what condition this is coming from, this is especially useful when debugging this kind of code, even more if you have several IF blocks within each other...
Avatar of aneesa83
aneesa83

Use Begin...End Block after IF statement