CASE Statement in WHERE statement (equal to and not equal to) - sql

I have the following query where I'm trying to return different values from a table based off the values of a bit variable.
Is there a way I can substitute the where condition to get that to work?
DECLARE #isAggregate bit = 0
SELECT
*
FROM
Fields
WHERE
FieldType
CASE
WHEN #isAggregate = 1 THEN = 'Aggregate'
WHEN #isAggregate = 0 THEN <> 'Aggregate'
END

You can use boolean logic, case expression will not work in this way :
where (#isAggregate = 1 and FieldType = 'Aggregate') or
(#isAggregate = 0 and FieldType <> 'Aggregate')

Related

Update multiple values using IS NULL condition

I just finished migrating an Access database to the SQL Server and I need to fix the Yes/No values to be defaulted to No as their data type conversion is set to bit.
I do this by setting the default value to 0.
However, I want to execute a query to do that as well, but there are multiple bit rows.
I know how to use multiples with the SET command, but how do we use multiple with WHERE? What is the proper way of structuring it?
UPDATE sometable SET
[isConditionOnePassed] = 0
, [isSecondPassed] = 0
, [isThirdPassed] = 0
WHERE [isConditionOnePassed] IS NULL, [isSecondPassed] is NULL, [isThirdPassed] IS NULL
Or is it with an AND? Like boolean logic?
UPDATE sometable SET
[isConditionOnePassed] = 0
, [isSecondPassed] = 0
, [isThirdPassed] = 0
WHERE [isConditionOnePassed] IS NULL and [isSecondPassed] is NULL and [isThirdPassed] IS NULL
Hmmm . . . If you want to set NULL values to another value, you can use COALESCE():
UPDATE sometable
SET isConditionOnePassed = COALESCE(isConditionOnePassed, 0),
isSecondPassed = COALESCE(isSecondPassed, 0),
isThirdPassed = COALESDCE(isThirdPassed, 0)
WHERE isConditionOnePassed IS NULL OR isSecondPassed is NULL OR isThirdPassed IS NULL;
Seems like what you really need is an ISNULL or CASE expression. Here is an example with both:
UPDATE dbo.SomeTable
SET isConditionOnePassed = ISNULL(isConditionOnePassed,0),
isSecondPassed = CASE isSecondPassed WHEN 1 THEN 1 ELSE 0 END;

Nested case conditionals in PostgreSQL, syntax error?

I use PostgreSQL and I would like to combine these two case conditions, but when I uncomment the code, I get a syntax error. This is not a difficult instruction. I want to divide or multiply the obtained number depending on the condition. How can I enter it so that the code is compiled?
SELECT
SUM(
CASE
WHEN transactions.recipient_account_bill_id = recipientBill.id AND recipientBill.user_id = 2
THEN 1
ELSE -1
END * transactions.amount_money
/* CASE
WHEN senderBillCurrency.id = recipientBillCurrency.id
THEN NULL
ELSE
CASE
WHEN recipientBillCurrency.base = true
THEN /
ELSE *
END senderBillCurrency.current_exchange_rate
END */
) as TOTAL
FROM transactions
LEFT JOIN bills AS senderBill ON senderBill.id = transactions.sender_account_bill_id
LEFT JOIN bills AS recipientBill ON recipientBill.id = transactions.recipient_account_bill_id
LEFT JOIN currency as senderBillCurrency ON senderBillCurrency.id = senderBill.currency_id
LEFT JOIN currency as recipientBillCurrency ON recipientBillCurrency.id = recipientBill.currency_id
WHERE 2 IN (senderBill.id, recipientBill.id)
You cannot create dynamic SQL expressions like that. A CASE expression cannot return an operator as if SQL was some sort of macro language. You can only return an expression.
You already used the following approach using 1 and -1 with your multiplication. Why not also use it with N and 1/N:
<some expression> * CASE WHEN condition THEN 1 / N ELSE N END
Or in your case:
<some expression> * CASE
WHEN senderBillCurrency.id = recipientBillCurrency.id THEN 1
WHEN recipientBillCurrency.base THEN 1 / senderBillCurrency.current_exchange_rate
ELSE senderBillCurrency.current_exchange_rate
END
Notice, you can put several WHEN clauses in a CASE expression. No need to nest them

SELECT WHERE {column} = CASE WHEN {expression} THEN NULL

I have this code which is part of a stored procedure
INSERT INTO #TempTable
/* A few subqueries, about 100 lines */
WHERE (cartera.ClaSucursal = #pIdSucursal OR #pIdSucursal = -1)
AND (cartera.ClaAsesorActual =
CASE
WHEN #pIdAsesor > 0 THEN #pIdAsesor
WHEN #pIdAsesor = 0 THEN NULL
END
OR #pIdAsesor = -1)
/* Rest of my code, about 200 lines */
SELECT * FROM #TempTable
Basically I have a parameter called #pIdAsesor and depending on its value there can be three possible outcomes.
#pIdAsesor = -1 which brings me all entries regardless of the Id value
#pIdAsesor = sumId which brings me all entries with given Id
#pIdAsesor = 0 which brings me all entries with NULL as the Id
Outcomes 1 and 2 work flawlessly, but scenario 3 doesn't bring back results.
null isn't a value - it's the lack thereof. null is never equal to anything (not even another null), but you can check for it explicitly with the is operator.
You could ditch the case expression and construct this logic with a series of ors:
AND ((#pIdAsesor = -1) OR
(#PIdAsesor = 0 AND cartera.ClaAsesorActual IS NULL) OR
(#pIdAsesor = cartera.ClaAsesorActual))
You can't use = for null in case when result comes null but = null doesn't work. You have to use is null.

How to set optional parameter for int type variable

Have two variable StatusTypeTestID and StatusTestID want to set them as optional in where clause as like bellow,but optional option not work for int variable.
Note: default value for int variable is 0
DECLARE #StatusTypeTestID as int
SET #StatusTypeTestID = 1
DECLARE #StatusTestID as int
SET #StatusTestID = 0
select *
from LiveCustomerStatus
where (StatusType=#StatusTypeTestID
and (Status = #StatusTestID or #StatusTestID is null))
As you were already trying, you can check if your parameters have been set as null or if they match the correspondent field.
This way you can leave a parameter as null if you want it to be optional, not affecting the result.
select *
from LiveCustomerStatus
where (#StatusTypeTestID is null or StatusType=#StatusTypeTestID)
and (#StatusTestID is null or Status = #StatusTestID)
option(recompile)
I have added a option(recompile) clause that will force SQL Server to recompile the query at every execution. This way it will use the appropriate indexes to optimize it depending of the value of the parameters (wether they are null or not).
You can comment both set statements and below query will work:
select * from LiveCustomerStatus
where (#StatusTypeTestID is null or StatusType=#StatusTypeTestID)
and (#StatusTestID is null or Status = #StatusTestID)
Use CASE Statement in WHERE clause :
SELECT *
FROM LiveCustomerStatus
WHERE StatusType = CASE WHEN ISNULL(#StatusTypeTestID,'') = '' THEN
StatusType ELSE #StatusTypeTestID END
AND Status = CASE WHEN ISNULL(#StatusTestID,'')= '' THEN Status ELSE
#StatusTestID END

Using CASE WHEN in a WHERE Statement to return ALL records if #parameter = 0

I am using Visual Studio 2008 and am in a report trying to create a query that has a WHERE statement that will return all records, if the #parameter = 0, otherwise I want the query to return only records that have the #paramete.
Here is the statement I envision, but can't seem to get correct:
WHERE (ADVISOR.staffPersonID = CASE WHEN #advisor = 0 THEN **'Do NOT
filter by staffpersonID'** ELSE #advisor END)
I have tried the following code which doesn't work:
CASE WHEN #advisor = 0 THEN ADVISOR.staffPersonID ELSE #advisor END
ADVISOR.staffPersonID is the field I would filter on, if the #parameter had a value other than 0. From what I've researched online, using the field itself as the THEN in the statement should work. It does, unless the table (advisor) has no records that match in it at all.
WHERE
(#advisor <> 0 AND ADVISOR.staffPersonID = #advisor)
OR
(#advisor = 0 )
try this:
WHERE ADVISOR.staffPersonID = #advisor OR #advisor = 0
WHERE ((ADVISOR.staffPersonID IS NULL AND #advisor = 0) 
OR (ADVISOR.staffPersonID  = CASE WHEN #advisor = 0 THEN 
ADVISOR.staffPersonID 
ELSE 
#advisor END
))