SQL Server IF EXISTS THEN 1 ELSE 2

使用 Sql Server 2012.我有一个存储过程,它的一部分检查用户名是否在表中.如果是,则返回 1,如果不是,则返回 2.这是我的代码:

Using Sql Server 2012. I have a stored procedure and part of it checks if a username is in a table. If it is, return a 1, if not, return a 2. This is my code:

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

但是,我不断收到以下错误:

However, I keep receiving the below error:

'1' 附近的语法不正确.

Incorrect syntax near '1'.

这甚至可以通过 IF EXIST 实现吗?

Is this even possible with an IF EXIST?

问候,

迈克尔

推荐答案

如果你想这样做,那么这就是你所追求的语法;

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

您并不严格需要 BEGIN..END 语句,但最好从一开始就养成这种习惯.

You don't strictly need the BEGIN..END statements but it's probably best to get into that habit from the beginning.

相关文章