SQL Server IF EXISTS THEN 1 ELSE 2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41015307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Server IF EXISTS THEN 1 ELSE 2
提问by Michael
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:
使用 Sql Server 2012。我有一个存储过程,它的一部分检查用户名是否在表中。如果是,返回 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
迈克尔
回答by Rich Benner
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
语句,但最好从一开始就养成这种习惯。
回答by AntDC
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。我相信它的成本最低。
回答by P?????
In SQL without SELECT
you cannot result anything. Instead of IF-ELSE
block I prefer to use CASE
statement for this
在没有SELECT
你的SQL 中,你不能产生任何结果。IF-ELSE
我更喜欢为此使用CASE
语句而不是块
SELECT CASE
WHEN EXISTS (SELECT 1
FROM tblGLUserAccess
WHERE GLUserName = 'xxxxxxxx') THEN 1
ELSE 2
END
回答by Zeina
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
回答by ahmed abdelqader
What the output that you need, select
or print
or .. so on.
什么输出需要,select
或print
或...等等。
so use the following code:
所以使用以下代码:
IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2
回答by Lakshmanan Dhamotharan
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