see sharp
see sharp

Reputation: 79

if/else condition in select statement

I want to verify if an employee exists in that client or not; if he does exist, then I want to show a message "success", else I want to show "invalid employee".

declare @Employeeid int

if @Employeeid = 1616
    select 
        @Employeeid = employeeindex 
    from 
        Employee_table
    where 
        clientid in (select Clientid 
                        from Employee_table 
                        where Clientid = 658)

    select * 
    from Employee_table 
    where Employeeid = @Employeeid

else
    raiserror ('Invalid Employee!', 16, 1)

return

This shows an error

Incorrect syntax near the keyword 'else'.

Upvotes: 1

Views: 558

Answers (2)

Stanislav Kundii
Stanislav Kundii

Reputation: 2894

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/if-else-transact-sql

Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE

Use BEGIN... END if need group statement for IF

Upvotes: 0

Ullas
Ullas

Reputation: 11556

Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed. BEGIN and END are control-of-flow language keywords.

Read here

Query

declare @Employeeid int

if @Employeeid = 1616
begin
    select @Employeeid = employeeindex 
    from Employee_table
    where clientindex in (select Clientid 
                          from Employee_table 
                          where Clientid = 658)

    select * 
    from Employee_table 
    where Employeeid = @Employeeid
end
else
    raiserror ('Invalid Employee! ', 16,1)

return

Upvotes: 1

Related Questions