Siddharth Bhardwaj Siddharth Bhardwaj - 1 month ago 5x
SQL Question

How to check whether a SQL query has executed successfully in a IF-ELSE Control Statement in SQL Server 2012?

Here i am storing department name in variable @department which i will be fetching from a row now for that particular department name i want to find out whether a department id exist or not in departments table means whether the department name entered by the user is a valid department or not,how to do this how do i turn this query into a Boolean expression?

create table dbo.departments(
department_id int primary key;
department_name varchar(255);

if(select @finaldepartment_id=department_id from dbo.departments where department_name like @department)
set @department_flag=1;
set @department_flag=0;


To check if there is any department that matches your condition use EXISTS

  select 1 
  from dbo.departments 
  where department_name like '%'+@department+'%'

If you need to assign an id from departments into a variable, set the variable with the result and then check if it's not null.