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:
Incorrect syntax near '1'.
Is this even possible with an 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.
How about using 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.
Its best practice to have TOP 1 1 always.
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.
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.
IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx')
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 2
END
In SQL without SELECT you cannot result anything. Instead of IF-ELSE block I prefer to use CASE statement for this
SELECT CASE
WHEN EXISTS (SELECT 1
FROM tblGLUserAccess
WHERE GLUserName = 'xxxxxxxx') THEN 1
ELSE 2
END
You can define a variable #Result to fill your data in it
DECLARE #Result AS INT
IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx')
SET #Result = 1
else
SET #Result = 2
What the output that you need, select or print or .. so on.
so use the following code:
IF EXISTS (SELECT * FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx') select 1 else select 2
Related
I've recently made a small application, that sends an e-mail.
I'm currently trying to have it send an e-mail whenever the latest record in an SSMS database, is older than 1 hour.
I'm using a case statement in the SQL query, to try and have the query return 1 or 0.
How would I make the SQL Query?
I'd hoped for an input like:
CASE
WHEN condition1 THEN result1
ELSE result
END;
Thank you in advance.
You can have a select statement, which checks if any record is found then return 1, else 0.
SELECT CASE
WHEN EXISTS (SELECT * FROM TableName WHERE datediff(hh,datecolumn,getdate())>1) THEN 1
ELSE 0 END AS NewRecordsFound
Or
SELECT IIF(EXISTS(SELECT * FROM TableName WHERE datediff(hh,datecolumn,getdate())>1),1,0) AS NewRecordsFound
Or
IF EXISTS(SELECT * FROM TableName WHERE datediff(hh,datecolumn,getdate())>1)
BEGIN
SELECT 1 AS NewRecordsFound
END
ELSE
BEGIN
SELECT 0 AS NewRecordsFound
END
I want to run a set of queries only if a few conditions are true. Please see one example below, I want to combine first 2 conditions and if they are true then enter begin block or else if only 3rd condition is true then enter begin block.
(If Exists(select top 1 * from table1 where [dateInTable]=#date )
and exists (select top 1 * from table2 where [dateInTable]=#date ))
-- Either above 2 are true collectively
OR
-- Or this should be true Individually
(IF exists(select top 1 * from table3 where [dateInTable]=#date))
Begin
-- Logic here
END
if i wrap these in parentheses it won't work and if i remove parentheses it might not consider OR condition as an individual condition and will discard if first 2 conditions are not true. that means 3rd condition will only be evaluated if first 2 are true.
Is this the logic you want?
if ( (exists (select 1 from table1 where [dateInTable] = #date) and
exists (select 1 from table2 where [dateInTable] = #date)
) or
exists(select 1 from table3 where [dateInTable] = #date)
)
begin
-- Logic here
end;
Note that select top 1 * in an exists is just wasted typing. The top does nothing. EXISTS just checks if a row is returned; the contents of the row are irrelevant. So, I just use 1 because it is easy to type.
SELECT 15 > 14 FROM Duel;
This code snippet is working in MySql but not in SQL Server:
SQL Error(102): Incorrect syntax near '>'
I have a requirement where I want to see if at least 1 record exist return 1 or else 0
SELECT count(emp.name) > 0
FROM ****
WHERE *** IN (***)
Check the db fiddle https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=348709a562ad02cbe88abf01a37229f1
I think you are looking for having
SELECT 1 from new_table_name
having count(empName)>0
Update
You can use SIGN(). It returns 1 when result is positive and 0 when the result is 0
SELECT SIGN(COUNT(*)) FROM new_table_name
Check fiddle here
Try case statement -
select case when count(emp.name) > 0 then 1 else 0 end
from ****
where *** IN (***)
You can try EXISTS clause
IF EXISTS (SELECT 1 emp.name
FROM ****
WHERE *** IN (***))
BEGIN
SELECT 1
END
ELSE
SELECT 0
END
As you want to return either 1 or 0, you need to define the values in CASE statement.
select case when exists(SELECT emp.name
FROM ****
WHERE *** IN (***)) then 1 else 0 end
Don't use COUNT. You don't want to count the rows, just to see if there is one. And don't use logic like IF, just use CASE.
SELECT CASE WHEN EXISTS (SELECT 1 FROM **** WHERE **** IN (****))
THEN 1
ELSE 0
END;
You may want to use a CTE like this:
WITH T (C)
AS
-- Select the first record with a value in emp.name
(
SELECT TOP 1 1
FROM **** emp
WHERE *** IN (***)
AND emp.name IS NOT NULL
)
-- just count the elements of T
SELECT COUNT(1) FROM T
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=3514827fadaf6b8d19c2658008df0a99
If you prefer the one-line solution without having to COUNT all records, here is an alternative:
SELECT IIF(exists(select TOP 1 1 from **** emp where emp.name IS NOT NULL), 1, 0)
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=be6c753a6ddb164524576061c3b8802e
All answer provided by is working fine. But SQL Server already provides comparison function.
SELECT IIF(count(erm.employee_code) > 0, 1, 0)
FROM ****
WHERE *** IN (***)
What is better approach to check existence of an object in database?
select count(id) as count from my_table where name="searchedName";
OR
select id from my_table where name="searchedName";
And then check if count > 0 or the object is not null (ORM logic)
EDIT:
select id to be valid for Oracle.
The idea should be to that we only need to find one record in order to say that such record exists. This can be done with an EXISTS clause in standard SQL.
select exists (select * from mytable where name = 'searchedName');
returns true if the table contains a record with 'searchedName' and false otherwise.
If you want 0 for false and 1 for true instead (e.g. if the DBMS does not support booleans):
select case when exists (select * from mytable where name = 'searchedName')
then 1 else 0 end as does_exist;
You say you want this for Oracle. In Oracle you can use above query, but you'd have to select from the table dual:
select case when exists (select * from mytable where name = 'searchedName')
then 1 else 0 end as does_exist
from dual;
But for Oracle we'd usually use rownum instead:
select count(*) as does_exist
from mytable
where name = 'searchedName'
and rownum = 1; -- to find one record suffices and we'd stop then
This also returns 1 if the table contains a record with 'searchedName' and 0 otherwise. This is a very typical way in Oracle to limit lookups and the query is very readable (in my opinion).
I'd just call:
select id from my_table where name='searchedName';
Making sure there is an index for the name column.
And then check whether or not the result is empty.
Try with IF EXISTS (
if exists (select 1 from my_table where name = "searchedName")
begin
....
end
Basically, what syntex would allow me to achieve the title statement?
If (select statement 1) returns 0 rows THEN (select statement 2) else (select statement 3)
So that the sql returns results from either statement 2 or 3
I've looked for a way to do this but nothing I've found so far seems to exactly address the if requirements.
IF EXISTS (SELECT field FROM table)
BEGIN
SELECT field FROM table2
END
ELSE
BEGIN
SELECT field FROM table3
END
Here you go...
IF ((select count(*) from table1)= 0)
BEGIN
Select * from table2
END
ELSE
BEGIN
SELECT * from table3
END
Sorry for the lack of feedback. Someone else in the office took an interest and came up with this:
select * from (
select *
, (SELECT Count(*)
FROM users
WHERE version_replace = 59 AND moderated = 1) AS Counter
FROM users WHERE version_replace = 59 AND moderated in (0,1)
) AS y
where Counter = 0 and Moderated = 0
or Counter > 0 and Moderated = 1
ORDER By ID DESC
Which does what I need.