简体   繁体   English

SQL Server IF EXISTS THEN 1 ELSE 2

[英]SQL Server IF EXISTS THEN 1 ELSE 2

Using Sql Server 2012. I have a stored procedure and part of it checks if a username is in a table.使用 Sql Server 2012。我有一个存储过程,它的一部分检查用户名是否在表中。 If it is, return a 1, if not, return a 2. This is my code:如果是,返回 1,如果不是,返回 2。这是我的代码:

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 1 else 2

However, I keep receiving the below error:但是,我不断收到以下错误:

Incorrect syntax near '1'. '1' 附近的语法不正确。

Is this even possible with an IF EXIST?这甚至可以通过 IF EXIST 实现吗?

Regards,问候,

Michael迈克尔

If you want to do it this way then this is the syntax you're after;如果你想这样做,那么这就是你所追求的语法;

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.您并不严格需要BEGIN..END语句,但最好从一开始就养成这种习惯。

How about using IIF?使用 IIF 怎么样?

SELECT IIF (EXISTS (SELECT 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx'), 1, 2)

Also, if using EXISTS to check the the existence of rows, don't use *, just use 1. I believe it has the least cost.另外,如果使用 EXISTS 来检查行是否存在,请不要使用 *,只需使用 1。我相信它的成本最低。

In SQL without SELECT you cannot result anything.在没有SELECT SQL 中,你不能产生任何结果。 Instead of IF-ELSE block I prefer to use CASE statement for this我更喜欢使用CASE语句而不是IF-ELSE

SELECT CASE
         WHEN EXISTS (SELECT 1
                      FROM   tblGLUserAccess
                      WHERE  GLUserName = 'xxxxxxxx') THEN 1
         ELSE 2
       END 

What the output that you need, select or print or .. so on.您需要什么输出, selectprint或......等等。

so use the following code:所以使用以下代码:

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2

Its best practice to have TOP 1 1 always.最佳做法是始终拥有TOP 1 1

What if I use SELECT 1 -> If condition matches more than one record then your query will fetch all the columns records and returns 1.如果我使用SELECT 1 -> 如果条件匹配多个记录,那么您的查询将获取所有列记录并返回 1。

What if I use SELECT TOP 1 1 -> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.如果我使用SELECT TOP 1 1 -> 如果条件也匹配多个记录,它只会获取任何行的存在(具有自 1 值列)并返回 1。

IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
BEGIN
   SELECT 1 
END
ELSE
BEGIN
    SELECT 2
END

You can define a variable @Result to fill your data in it你可以定义一个变量@Result来填充你的数据

DECLARE @Result AS INT

IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') 
SET @Result = 1 
else
SET @Result = 2

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

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