Switch case in where clause (sql server) - sql-server

I want to use case in sql statement where clause but I have a problem as I want to create a where clause condition on the basis of some value and I want to set a not in clause values on the basis of it
here is the query where am facing an issue
WHERE CODE = 'x' and
ID not in (
case
when 'app'='A' then '570','592'
when 'Q' then ID 592,90
else 592,90
END
but its not syntax

You could embed it into the SQL where clauses like this:
WHERE CODE='x' and (('app' = 'A' AND ID not in ('570', '592')) OR
('app' = 'Q' AND ID not in ('592','90')) OR ('app' != 'A' AND 'app' != 'Q' AND ID not in ('592','90'))
Or something like that. Creepy code though, so I'd suggest using different queries for different types of 'app' parameter or create a stored procedure to handle your needs.

Consider that you may be trying to combine what should actually be separate statements.
You may want to consider using a test condition (perhaps via a simple IF statement) to determine which specific T-SQL statement to actually execute.
Pseudo Code:
IF (/*Conditions are True*/)
BEGIN
--SQL Statement
END
ELSE IF (/*Some other conditions are True)
BEGIN
--SQL Statement
END
ELSE
BEGIN
--Failsafe SQL statement
END
The logical intent of the code produced will be much easier to understand and maintain going forward.

As 592 is always part of the set, and the "Q" case is the same as the default, just do like this:
where CODE = 'x' and ID not in (592, case app when 'A' then 570 else 90 end)

Related

Wrapping ISNULL around NULLIF

Suppose that I have:
case
when #ID ='2386002' then ISNULL(nullif(i.call,''),i.standingOrderNumber)
when nullif(rtrim(i.call),'') is null then
nullif(rtrim(i.standingOrderNumber), '')
else case when nullif(rtrim(i.standingOrderNumber),'') is null then rtrim(i.call)
else
rtrim(i.call)
This is just a part of the procedure which does synchronization between two apps, the problem is that standingOrderNumber is not synchronized and I assume it has to to do with this code portion.
Scenario:
After entering call and standingOrderNumber like this:
call: '' (leave it empty)
standingOrderNumber: 777777
Data is stored in a table and procedure takes the data from that table and displays it on the app form, problem is, everything is displayed correctly, except for this standingOrderNumber.
Can you tell if something went wrong in the logic I submitted above ?
I think problem with the below line,
when #ID ='2386002' then ISNULL(nullif(i.call,''),i.standingOrderNumber)
here you are trying to check i.call for null value and replacing it with empty string and that makes ISNULL function useless.
Solution is not to use nullif in above line

SQL Report Error - [Macromedia][SQLServer JDBC Driver][SQLServer]Invalid column name

We use a housing software based on ColdFusion and uses SQL to create database functions in our reports. I am working on a custom report to try to subtract one column from another: more specifically subtract COUNT_OF_INSPECTION_TYPE from OCCUPANCY. The OCCUPANCY column is based on the following code:
CONVERT(INT
, CASE
WHEN tblHalls.HALLNAME = 'Hall1' THEN 198
WHEN tblHalls.HALLNAME = 'Hall2' THEN 430
WHEN tblHalls.HALLNAME = 'Hall3' THEN 333
END
)
When I try a new function OCCUPANCY - COUNT_OF_INSPECTION_TYPE, I get an error:
Unable to invoke CFC - Error Executing Database Query. [Macromedia][SQLServer JDBC Driver][SQLServer]Invalid column name
'OCCUPANCY'.
I'm not sure if I am explaining this right. I'd appreciate any help you can offer.
You cannot create an alias and use it in another calculation, at the same level, because the alias is not defined yet. Either repeat the whole CASE ... END statement in the calculation (less desirable) OR use another option, such as a CTE, derived table, APPLY operator, etcetera.
Wrapping your existing SELECT in a CTE is probably one of the simplest options:
;WITH cte
AS
(
-- Your current SELECT statement goes here
SELECT
CONVERT(INT
, CASE
WHEN tblHalls.HALLNAME = 'Hall1' THEN 198
WHEN tblHalls.HALLNAME = 'Hall2' THEN 430
WHEN tblHalls.HALLNAME = 'Hall3' THEN 333
END
)
AS OCCUPANCY
, tblHalls.COUNT_OF_INSPECTION_TYPE
, ... (Other Columns)
FROM tblHalls
)
-- Now use the alias in a calculation
SELECT cte.*
, cte.OCCUPANCY - cte.COUNT_OF_INSPECTION_TYPE AS SomeAliasForThisCol
FROM cte
Side note, since the CASE statement does not define an ELSE condition, the result of the calculation will be NULL if none of HallName's match. If that is not desirable, consider setting a default.

SQL Server : only display results of stored procedure under certain conditions

I'm currently working on a stored procedure that creates a table with many columns with many conditions. One of the requirements of this proc is that when column A has a value of YES then Column B must have a value. I have no idea how to code this but I was leaning towards a case statement in the where clause along these lines
CASE WHEN Table.A = 'YES' then Table.B is not NULL end
You can transform it to
Where (Table.A = 'YES' and Table.B is not NULL)
OR Table.A <> 'YES'
May be you should add the full query to get it added in right way to the query
I'm assuming you need to include other logic in your process, which you can achieve by nesting case statements like the below. If not, Prdp's answer will be sufficient for your needs.
where case when Table.A = 'YES'
then case when Table.B is not null
then 1
else 0
end
else 0
end = 1

SQL Server : While loop with nested If

I'm creating a stock market database and am stumped that the following works correctly EXCEPT for the last select that returns results (after which the select does not change on subsequent loops). I've tried to simplify the code as follows, thanks in advance for feedback (I'm still noob):
Three tables:
BuyOrders
SellOrders
MatchedOrders
Stored procedure to process a NewBuyOrder:
Insert NewBuyOrder to BuyOrders;
While (NewBuyOrder.SharesRemaining > 0 )
SELECT TOP 1
FROM SellOrders
WHERE SellOrders.Price <= NewBuyOrder.Price
ORDER BY SellOrders.Price, SellOrders.TimePlaced;
IF NewBuyOrder.SharesRemaining < SellOrders.SharesAvailable
UPDATE SellOrders.SharesAvailable = [difference];
UPDATE BuyOrders = 0;
INSERT INTO MatchedOrders;
SET NewBuyOrder.SharesRemaining = 0;
BREAK;
ELSE
UPDATE SellOrders = 0;
UPDATE BuyOrders = [difference];
INSERT INTO MatchedOrders;
SET NewBuyOrder.SharesRemaining = [difference];
CONTINUE;
In hope it might help someone else, I found the issue . . . I'm using local variables to store the matched SellOrderID. As such if the Select returns no match on a second pass through then the local variables were not getting updated (and hence erroneously reused in subsequent while loops until the If kicked in).
So I put a SET SellOrders.ID = 0 into the WHILE loop before the Select then below the Select added a IF SellOrders.ID = 0 and inside that a SET NewBuyOrder.SharesRemaining = 0 and BREAK (then made the first IF above into an ELSE IF).
I need to revisit the process to see if I can make it more elegant but would sincerely welcome thoughts on better ways to accomplish a process for matching the best available counteroffers in sequence. I've read but don't know much about cursors, plus think it transactionally superior not to SELECT a prioritized table of all matches rather than using my iterative loop -- but also have read suggestions not to use loops in SQL. Comments?
In addition I note the following: By itself a Select with no results returns a null set. Thus my original plan was to Select into my SP local variables and then use an IF EXISTS. I assume the local variable exists upon instantiation (even with no value) but am surprised that after a Select into the local variable with no results also did not fail an IF NULL test (i.e. presumably NULL cannot be inserted into a variable). What then is the value of an instantiated local variable with no value -- Blank?

How to use If Else Condition in Where Clause in SQL Server for Date Columns?

I want to use if else in where condition for Date Coulmns. Actually what i want to do is:
I have a table, which having two columns, CreatedDate and LastModifiedDate. Now what i want to check in Stored Proc is:
if LastUpdateDate is null then it will check for CreatedDate.
Below is my query:
SELECT isnull(SSA.UpdateDateTime,
isnull(SSA.CreateDateTime,'')) as LastUpdateAnswerDateTime
from SI_SurveySiteAnswer SSA
WHERE SSA.UpdateDateTime IS NOT NULL
There are other number of table in joins i am just pasting the required query only. how can i go for the check i am totally confused.
Please help me..
UPDATED:
I have write the below code, please confirm if it is the correct way to use If in where
SELECT isnull(SSA.UpdateDateTime,
isnull(SSA.CreateDateTime,'')) as LastUpdateAnswerDateTime
from SI_SurveySiteAnswer SSA
WHERE SSA.UpdateDateTime = ISNULL(SSA.UpdateDateTime,SSA.CreateDateTime)
I think i was not able to make my requirement very clear in first go, let me explain here..
i have a survey question answer table, i want to send an email notification if question has been answered, now answer can answered in one go, in that case createddate will have value not the updateddatetime,
Second case is:
answer is being updated in second go, then i need to check for the LastUpdateDateTime..
That's what i want to make in query.
You don't need any if / else functionality, just use the or operator to check that either is not null:
WHERE SSA.CreateDateTime is not null OR SSA.UpdateDateTime is not null
You can use COALESCE if you want this functionality, here are some sites for your reference.
http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/
http://sqlmag.com/t-sql/coalesce-vs-isnull
you can use case
SELECT Isnull(SSA.updatedatetime, Isnull(SSA.createdatetime, '')) AS
LastUpdateAnswerDateTime
FROM si_surveysiteanswer SSA
WHERE SSA.updatedatetime = CASE
WHEN SSA.updatedatetime IS NULL THEN
#SSA.createdatetime
ELSE SSA.updatedatetime
END
Try case statement.
SELECT isnull(SSA.UpdateDateTime,
isnull(SSA.CreateDateTime,'')) as LastUpdateAnswerDateTime
from SI_SurveySiteAnswer SSA
WHERE CASE WHEN SSA.UpdateDateTime IS NULL THEN SSA.CreateDateTime
ELSE SSA.UpdateDateTime END IS NOT NULL

Resources