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 (***)
Related
I want to select from one table based on who run the SP. For example if executer has Management role the they can see all records but if executer is Employee then they just see records for all employees. There are some roles like Seller, StockKeeper , ... .
Please consider this sudo code, I want to write a code like this but I got error:
Declare #Role varchar(30)
select *
from MyTable
where Status in (IIF(#Role = 'Employee', select -1 , select -1, 0, 1))
OR
select *
from MyTable
where Status in (case #Role when 'Employee' then select -1 else select -1, 0 , 1 end)
Error:
Incorrect syntax near the keyword 'select'.
Incorrect syntax near the keyword 'else'.
Incorrect syntax near ')'.
Is there any way to combine inline SELECT and IN operator?
Thanks
Edit 1)
Sample Data:
Id Value Status
----------------------------
1 10 -1
2 20 0
3 30 -1
4 40 1
5 50 -1
6 60 0
7 70 1
8 80 -1
for Employee I want to get this result:
Id Value Status
----------------------------
1 10 -1
3 30 -1
5 50 -1
8 80 -1
for Manager I want to get All records.
Use UNION to build the full list of allowable statuses in a conditional manner:
SELECT *
FROM MyTable
WHERE [Status] IN (
-- Everyone gets this role
SELECT -1
UNION ALL
-- Only special people get this role
SELECT 0
WHERE #Role <> 'Employee'
-- Only special people get this role
UNION ALL
SELECT 1
WHERE #Role <> 'Employee'
);
Assuming your sample data is reflective of the bigger picture you could simplify that down to:
SELECT *
FROM MyTable
-- Everyone gets this status
WHERE [Status] = -1
-- Only special people get these statuses
OR (#Role <> 'Employee' AND [Status] IN (0, 1);
Notes:
CASE is an expression i.e. returns a scalar value. Its not a switch statement.
Sub-queries require brackets around them, so even if case allowed it you would still need (select -1) rather than select -1.
If I understand correctly, you can try to use conditions to judge your expected result.
if your input #Role is Manager get all data, otherwise Employee will get -1
Declare #Role varchar(30)
SELECT *
FROM MyTable
WHERE (#Role = 'Employee' AND Status = -1)
OR (#Role = 'Manager')
sqlfiddle
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
This question already has answers here:
Return a value if no record is found
(6 answers)
Get 0 value from a count with no rows
(6 answers)
Closed 7 years ago.
I have a simple query:
Select qty from X where id=....;
this query always return 0 or 1 row.
when it return 1 row everything works.
but if it return 0 rows my query fails as qty is used in calculations. (This is acatually a Sub query in Select statment).
I need somehow to make sure the query always return 1 row.
I tried:
Select coalesce(qty,0) from X where id=....;
but it doesn't help as if there are no rows the coalesce is useless.
if no row found it should give 0
How can I fix it?
You can do this:
SELECT COALESCE( (SELECT qty from X where id=....), 0)
if nothing is returned from the inner SELECT statement, COALESCE will give you 0 in the outer SELECT statement.
Select *.a from (
Select qty, 0 as priority from X where id=....
Union
Select 0, 1 as priority
) a
Order By a.priority Asc
Limit 1
This select basically ensures that at least one row is returned by adding an additional row to the end and by adding the limit statement we just return the first row.
So now there is the case where at least one row is found and the additional row is added to the end. In this case the first row found (see ->) will be returned due to the ascending order by priority:
qty priority
-> 1 0
3 0
4 0
. .
0 1
And then there is the case where no row is found but the additional row is returned:
qty priority
-> 0 1
try this.
SELECT COALESCE((SELECT qty
FROM x
WHERE id = #MyIdVar), 1)
If no records found then its return 'No rows found'
if not exists(Select * from table where condition=...)
Begin
Select * from table where condition=...
End
Else
Begin
Select 'No rows found'
End
Whenever you use this you will get record else no record found message.
Without using COALESCE()
select qty from X where id=1 UNION SELECT 0 order by qty desc limit 1
Demo
I am attempting to create a row called Flag that will keep a count of when Value is above 2. Later I will need to sum flag as a count.
I currently have:
CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag',
CASE
WHEN 'Flag' = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
I receive the error:
Conversion failed when converting the varchar value 'Flag' to data
type int.
How can I force the 1 or 0 to be an INT in order to do later math?
I've looked around and I can't seem to find a way that fits.
To be able to use previously created columns in the select, you'll need to use for example outer apply, with something like this:
select
*
from table1
outer apply (
select CASE WHEN Value > 2 THEN 1 ELSE 0 END AS Flag
) X
outer apply (
select CASE WHEN X.Flag = 1 THEN 1 ELSE 0 END AS FollowedUpCorrectly
) Y
Test this in SQL Fiddle
You could use CTE or a subquery to create a flag and then do your case statement as needed in the outer query like this:
;WITH q1
AS (
SELECT
col1
,col2
,col3
,CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag'
FROM your_table --change this to match your table and column name
)
SELECT q1.col1
,q1.col2
,q1.col3
,CASE
WHEN q1.Flag = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
FROM q1;
I might misunderstand what you are after.
CASE
WHEN Value > 2
THEN 1
ELSE 0
END AS 'Flag',
CASE
WHEN 'Flag' = 1
THEN 1
ELSE 0
END AS 'FollowedUpCorrectly'
If these two lines are in the same code block, 'Flag' is unknown in the second Case Statement.
Update: As Siyual has pointed out, Flag is a string literal. Try changing the name to something that is not a reserved word.
You are comparing a string ('Flag') to an int (1). Perhaps you meant to refer to the first case that you named 'Flag'. If so, try referring to it without using the single quotes. Then the analyzer will recognize it and accept it as an int, which it is. But 'Flag' is a string. Flag is an int.
I basically want to do this:
SELECT HasComments = CASE (LEN(Comments) > 1) WHEN 1 THEN 1 ELSE 0 END FROM TableName
In other words, return a boolean telling me whether the length of Comments is greater than 1. This gives me a syntax error.
How can I accomplish this?
SELECT HasComments = CASE WHEN LEN(Comments) > 1 THEN 1 ELSE 0 END
FROM TableName
A better way would be to make Comments NULLable and check for that. Indexes could then be leveraged instead of the table-scan LEN() will cause.
you're missing the when and end
SELECT HasComments = CASE WHEN (LEN(Comments) > 1) WHEN 1 THEN 1 ELSE 0 END
FROM TableName
Since you have no WHERE clause, you're most likely returning a column of data:
SELECT CASE WHEN LEN(Comments) > 1 THEN 1 ELSE 0 END as 'HasComments'
FROM TableName
For newer SQL versions:
SELECT CASE WHEN LEN(Comments) > 1 THEN 1 ELSE 0 END FROM TableName