Gary Senter
Gary Senter

Reputation: 29

SQL varaibles if statement

I have a issue resulting in the following error.

declare @transDate datetime = GETDATE();
declare @main_work_center as varchar(50) = 'PMOM';
declare @team as varchar(1) = '';
declare @full_work_center as varchar(50);
IF(@team = '' OR @team IS NULL) then
    @full_work_center = @main_work_center;
else
    @full_work_center = @main_work_center + @team;
end if

THis is the error: Msg 156, Level 15, State 1, Line 5 Incorrect syntax near the keyword 'then'.

Upvotes: 0

Views: 31

Answers (1)

alroc
alroc

Reputation: 28174

You have multiple syntax errors in your code, that's just the first.

  1. then is not allowed with an if
  2. You need a set before your variable assignments in the if/else
  3. There is no if after the end

I like to wrap the code inside the two blocks of an if/else with begin and end, much like the curly braces in other languages, for clarity.

Fully corrected code:

declare @transDate datetime = GETDATE();
declare @main_work_center as varchar(50) = 'PMOM';
declare @team as varchar(1) = '';
declare @full_work_center as varchar(50);
IF(@team = '' OR @team IS NULL) 
begin
    set @full_work_center = @main_work_center;
end
else
begin
    set @full_work_center = @main_work_center + @team;
end;

Upvotes: 2

Related Questions