Chelsea
Chelsea

Reputation: 13

SQL IF AND ELSE STATEMENT

I have been trying to execute this if and else statement. However every execution indicates error such as either functional error or syntax related errors.

CREATE trigger [dbo].[TRIAL]
on [dbo].[TBL1]

after INSERT 
AS 
BEGIN
    SET NOCOUNT ON;

    IF TBL1.NUMBER = TBL2.NUMBER  THEN    
      insert into TBL3 (NAME,HEIGHT)    
      select NAME,HEIGHT    
      from TBL1,TBL2  

   ELSE     
      PRINT 'WRONG NUMBER'

end 

Would you please be able to help me to correct this?

Upvotes: 0

Views: 170

Answers (1)

Joe Farrell
Joe Farrell

Reputation: 3542

To expand a bit on Alex K's comment:

declare @Flag bit = 1;

-- ERROR: There is no THEN keyword.
if @Flag = 1 then
    select 'A';

-- CORRECT: Omit THEN and this works as expected.
if @Flag = 1
    select 'A';


-- ERROR: Only the first SELECT is associated with the IF, so the ELSE is unmatched.
if @Flag = 2
    select 'B1';
    select 'B2';
else
    select 'C';

-- CORRECT: If each branch of the IF has only one statement, then this construction is okay.
if @Flag = 2
    select 'B1';
else
    select 'C';

-- CORRECT: If you want multiple statements in either branch of the IF, make them into a block using BEGIN/END.
if @Flag = 2
begin
    select 'B1';
    select 'B2';
end
else
    select 'C';

-- CORRECT: You can also use BEGIN/END with single statements if you like. 
if @Flag = 2
begin
    select 'B1';
    select 'B2';
end
else
begin
    select 'C';
end

Upvotes: 4

Related Questions