My question is a bit more generic, but let's say I want to test some expression in SQL Server. I write SELECT 1=1 or SELECT 'a' > 'B' and press F5, hoping to see the result, like I do when I type SELECT 0, 1.
But I get an error instead. Why is that? What should I use to evaluate those expressions on the fly?
SQL Server doesn't have a boolean data type.
You would need to use SELECT CASE WHEN 1=1 THEN 1 ELSE 0 END
Simplest way is to select 1 where <test expression here>
You could put your expression after where like this
select 'true' where 1=1
select 'true' where 1<>1
of you could put it in an IF statement
IF 1+1=2
BEGIN
PRINT 'One and one makes two.'
END
You could use a case statement:
select case when 1=1 then 'true' else 'false' end
select case when 'a'>'B' then 'true' else 'false' end
or an IF...ELSE
if 1=1
select 'true'
else
select 'false'
if 'a' > 'B'
select 'true'
else
select 'false'
You can use the following to turn the output of the comparison to pseudo-boolean:
select isnull((select 'false' where not(1**0=1**)) ,'true')
or, to have an int as return:
select isnull((select 1 where 1<1) ,0)
Related
I have below dynamic WHERE condition in XML mapping which is working fine:
WHERE
IncomingFlightId=#{flightId}
<if test="screenFunction == 'MAIL'.toString()">
and ContentCode = 'M'
</if>
<if test="screenFunction == 'CARGO'.toString()">
and ContentCode Not IN('M')
</if>
order by ContentCode ASC
I'm trying to run below query in a IDE but unfortunately its not working.
Can anybody please explain what i'm doing wrong?
WHERE
IncomingFlightId = 2568648
AND (IF 'MAIL' = 'MAIL'
BEGIN
SELECT 'and ContentCode = "M"'
END ELSE BEGIN
SELECT 'and ContentCode Not IN("M")'
END)
order by ContentCode ASC
You can't use IF in straight up SQL statement, use CASE WHEN test THEN returniftrue ELSE valueiffalse END instead (if you have to use conditional logic)
That said, it's probably avoidable if you do something like this:
WHERE
(somecolumn = 'MAIL' AND ContentCode = 'M') OR
(somecolumn <> 'MAIL' and ContentCode <> 'M')
Example of conditional logic in a straight SQL:
SELECT * FROM table
WHERE
CASE WHEN col > 0 THEN 1 ELSE 0 END = 1
Case when runs a test and returns a value. You always have to compare the return value to something else. You can't do something that doesn't return a value.
It's kinda dumb here though, because anything you can express in the truth of a case when, can be more simply and readably expressed in the truth of a where clause directly..
SELECT * FROM table
WHERE
CASE WHEN type = 'x'
THEN (SELECT count(*) FROM x)
ELSE (SELECT count(*) FROM y)
END = 1
Versus
SELECT * FROM table
WHERE
(type = 'x' AND (SELECT count(*) FROM x) = 1) OR
type <> 'x' AND (SELECT count(*) FROM y) = 1)
It's useful for things like this though:
SELECT
bustourname,
SUM(CASE WHEN age > 60 THEN 1 ELSE 0 END) as count_of_old_people
FROM table
GROUP BY bustourname
If you're looking to write a stored procedure that conditionally builds an SQL, then sure, you can do that...
DECLARE #sql VARCAHR(max) = 'SELECT * FROM TABLE WHERE';
IF blah SET #sql = CONCAT(#sql, 'somecolumn = 1')
IF otherblah SET #sql = CONCAT(#sql, 'othercolumn = 1')
EXEC #sql...
But this is only in a stored procedure or procedure-like sql script where it builds a string that looks like an SQL, and then executes it dynamically. You cannot use IF in a plain SELECT statement
You are running the query which (beside it is syntactically incorrect SQL) has nothing to do with query generated and used by mybatis.
You need to understand how if in mybatis mapper works.
if element evaluates before the query is executed at the stage of generation of the SQL query text. If the value of the test is true the content of if element is included into the resulting query. In your case depending on the screenFunction parameter passed to mybatis mapper method one of three conditions are generated.
If value of screenFunction is MAIL then:
WHERE
IncomingFlightId=#{flightId}
and ContentCode = 'M'
order by ContentCode ASC
If value of screenFunction is CARGO then:
WHERE
IncomingFlightId=#{flightId}
and ContentCode Not IN('M')
order by ContentCode ASC
Otherwise (if value of screenFunction is not MAIL and is not CARGO):
WHERE
IncomingFlightId=#{flightId}
order by ContentCode ASC
Only after the query text is generated it is executed via JDBC against the database.
So if you want to run the query manually you need to try one of these queries.
One thing that you may want to do to make it easier is to enable logging of SQL queries and parameters passed to them so you can more easily rerun them.
When i run this query i expect the result will be 'false'
IF isnull(0,'') = ''
select 'true'
else
select 'false'
But sql Server tells me 'true', why?
In this case ISNULL(0,'') returns an integer. SQL Server will cast the second argument to an integer too, ie 0. So 0=0, hence the result is TRUE. Comparing directly to 0 would also return true:
IF 0 = ''
select 'true'
else
select 'false'
Using ISNULL and NULL like this is unusual. An ISNULL(someColumn='') function in a WHERE clause would prevent the optimizer from using any indexes that covered someColumn thus forcing a scan instead of an index seek.
Using IF statements in SELECT is impossible. Even in CASE statements, it's better to explicitly check for NULL than apply such transformations.
For your case, when compare two values, the '' will be converted to int first. The following:
SELECT CONVERT(INT, '')
returns 0, so 0=0 is true
If you want treat 0 as NULL, you can use NULLIF:
DECLARE #i INT = 0
IF NULLIF(ISNULL(#i, ''), 0) = ''
SELECT 'true'
ELSE
SELECT 'false'
This would return 'false'
ISNULL are identical when there are just two values (i.e. NULL and 0) so, it will be true in IF condition and select 'true' will be printed.
I'm trying to understand how nullif is working. I have an error in this statement
select
case 'Null if equal'
when (MakeFlag = FinishedGoodsFlag) then null
else 1
end
from
Production.Product
I get an error:
Incorrect syntax near '='.
So any help ? Thanks in advance
I guess you want to use NULLIF which returns null if both are equal, or else the first expression:
SELECT [Null if equal] = NULLIF(MakeFlag, FinishedGoodsFlag)
FROM Production.Product
select case
when (MakeFlag = FinishedGoodsFlag) then null
else 1
end as 'Null if equal'
from Production.Product
I think this would help you
Your syntax is not correct, I think this should be:
select case when (MakeFlag = FinishedGoodsFlag) then null
else 1
end as 'Null if equal'
from Production.Product
Not sure where 'NullIf' comes into this.
I have a simple query and all I want to do is check if this variable is true or false, and for some reason it always returns false.
DECLARE #CappedIFCheck BIT
SET #CappedIFCheck = (SELECT distinct 1
FROM mytable
WHERE 1=1);
select #CappedIFCheck
IF (#CappedIFCheck = 'True')
BEGIN
SELECT 'true';
END
ELSE
BEGIN
SELECT 'false';
END
When comparing BIT values in Sql Server, use literal values 1 and 0 instead of 'True' and 'False'.
IF (#CappedIFCheck = 1) ...
A bit variable in SQL Server can have three values. 0, 1 and NULL.
The strings 'true' and 'false' map to 1 and 0 respectively.
Your code does not take account of the third possible value. If mytable is empty then the variable will not be initialised and have the value NULL.
SELECT CASE #CappedIFCheck
WHEN 'True' THEN 'true'
WHEN 'False' THEN 'false'
ELSE 'unknown'
END
I'm not sure exactly what your code is trying to do but that is a very inefficient way of going about things. You should use EXISTS instead.
Try the set clause like this:
SET #CappedIFCheck = ISNULL((select 1 where exists (select 1 from MyTable where 1=0)),0)
I am writing a CASE statement in my SQL Server Stored Procedure. There I am repeeating a same long SQL statements every time for 11 CASEs. Should I put the SQL Statement in CASE condition in a another Stored Procedure? What could be the best approach?
CASE (SELECT ..................)
THEN 'SELCET a.field'
ELSE
''SELECT vlaues'
END
as 'Coulmn1 '
CASE (SELECT ..................)
THEN 'SELCET vaues'
ELSE
''SELECT vlaues'
END
as 'Coulmn1 '
You might want to do something like
SELECT
CASE (your select statement which retuns one value)
WHEN 'option1' THEN 'value2return1'
WHEN 'option2' THEN 'value2return2'
WHEN 'option3' THEN 'value2return3'
...
ELSE 'defaultValue'
END
Use common table expressions link.
WITH CTE (ColA)
AS
(
Select ColA From Table
)
SELECT ColA
FROM CTE
Use a CTE. In the future it would help if you gave us a slightly better example of your code however.
WITH RepeateSelect AS (SELECT ..................)
.....
.....
CASE (SELECT * FROM RepeateSelect)
THEN 'SELCET a.field'
ELSE
'SELECT vlaues'
END
as 'Coulmn1 '
CASE (SELECT * FROM RepeateSelect)
THEN 'SELCET vaues'
ELSE
''SELECT vlaues'
END
as 'Coulmn1 '
Try using the repeated query once thusly:
select A.C1, X.C2, X.C3
from TableA as A inner join
( select B.AlmondJoy,
case when B.YN > 7 then 'Yes' else 'No' end as C2,
case when C.UD in ( -1, 1 ) then 'Up' else 'Down' end as C3
from TableB as B inner join
TableC as C on C.Id = B.Id
) as X on X.AlmondJoy = A.Zagnut