简体   繁体   English

如何检查SQL Server 2012的IF-ELSE控制语句中是否已成功执行SQL查询?

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

I am storing department name in a 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 exists or not in departments table means whether the department name entered by the user is a valid department or not. 我将部门名称存储在变量@department ,现在将从该行中获取该特定部门名称。我想找出departments表中是否存在部门ID,这表示用户输入的部门名称是否为是否有效的部门。 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;
else
   set @department_flag = 0;

It can be simplified to single query 可以简化为单个查询

SET @department_flag = CASE 
                         WHEN EXISTS (SELECT 1 
                                      FROM   dbo.departments 
                                      WHERE  department_name LIKE Concat('%',@department,'%')) THEN 1
                         ELSE 0 
                       END 

To check if there is any department that matches your condition use EXISTS 要检查是否有符合您条件的部门,请使用EXISTS

IF 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. 如果您需要将部门的ID分配给变量,请为变量设置结果,然后检查其是否不为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM