SQL server: where clause for optional fields - sql-server-2008

Track Id is optional field in my application.
Case 1: If I pass valid track id, it should return the respective rows.
Case 2: If invalid track id is passed, no rows should be returned.
Case 3: If no track id passed, all rows should be returned
DECLARE #transaction_ID INT
SELECT #transaction_ID = Transaction_ID FROM myTable WHERE TRACK_ID= #Track_Id
My where condition is:
WHERE (#transaction_ID IS NULL OR myTable.Transaction_ID = #transaction_ID)
AND (amount<>0)
with the above condition 1 and 3 cases are working fine. but 2nd case got failed. When I passed invalid track id, all rows are getting returned. Please correct the query to handle the case 2. Thanks in advance.

Just continue to query #Track_ID as well:
WHERE (
(#transaction_ID IS NULL AND #Track_Id IS NULL) OR
myTable.Transaction_ID = #transaction_ID)
AND (amount<>0)
(The only situation where you want a NULL #Transaction_ID to make this WHERE clause succeed is case 3. In Case 2, a non-null #Track_Id was passed but #Transaction_ID will be NULL because no rows were returned, so that's the situation we're trying to deal with)

Try something like this
Where 1=(Case when #TrackId = 1 Or TRACK_ID= #Track_Id then 1 else 0 end )
When you want all the data then pass 1 ,
When want data as per TrackID pass #trackID value and
when you dont wnat the condition to be applied pass null

Related

SQL Bind multiple fields condition as AND clause

Can someone help me with this SQL.
Output must always join the day_ids as multiple condition.
For instance, if we choose day_id IN (0,2,4), it must return ONLY all data with day_ids (0,2,4). It works fine.
So when we input (0,2,4,5), it must not return any data. This is where the issue occurs.
Since IN clause follows the OR statement, it still gives the same result instead of returning NULL.
Sample data: https://drive.google.com/file/d/1rXjOPxFRmtDjdyD4bDvULP-m38G5GvIB/view
Video : https://drive.google.com/file/d/1WM42cmmMe1nCusqacJNS_MI2t9szgZGn/view?usp=sharing
Any idea will be greatly appreciated.
https://i.stack.imgur.com/lWfdy.png
https://i.stack.imgur.com/s0Ala.png
SELECT * FROM vw_transfer_sched WHERE day_id in (0,2,4,5)
GROUP BY week_num, day_id, teacher_id
HAVING COUNT(distinct day_id) = 4;
SELECT * FROM vw_transfer_sched CASE WHEN day_id IN (0,2,4) THEN day_id ELSE Null END;
That should give you Null if there are no rows containing 0,2,4
Instead of sending your desired must exits day_ids to the query, you can find out if all those day_ids exist with help of a different query and compare it outside and if they all exist then you can run the query that you have attached.
You can compare the result of the following query with your desired must exist day_ids.
select group_concat(distinct day_id)
from teacher_availability_list
where day_id in (0,2,4,5)
With the table that you have attached it will return 0,2,4.
you can do this outside of the query or in a stored procedure.
IF (result of the above query) = the desired must have day_ids
then -> run the query
else
return null
try
select t.*
from
( SELECT *
FROM teacher_availability_list
GROUP BY week_num, teacher_id, day_id
order by week_num, teacher_id ) as t
group by week_num, teacher_id
having group_concat(t.day_id)='0,1,2'

Best way to store configuration in MySQL

I have a scenario where i need to store configurations in mysql table having three columns namely VendorID,ServiceID and ModeID . Configuration for a vendor can be done with three overriding cases as follows.
One column VendorID having non-NULL value with ServiceID ,ModeID having NULL value.
VendorID,ServiceID,ModeID -- > 1,NULL,NULL
Two columns VendorID,ServiceID having non-NULL values with ModeID having NULL value.
VendorID,ServiceID,ModeID -- > 1,1,NULL
All three columns having non NULL values.
VendorID,ServiceID,ModeID -- > 1,1,1
When case 1,2,3 are defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 3 overrides case 2 and case 1.
When case 3 is not defined and case 1,2 are defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 2 overrides case 1.
When case 3 and case 2 are not defined and case 1 is defined and in the MySQL query WHERE clause vendorid,servideid and modeid are passed, then case 1 is returned.
Now my question is, how can i query the table to get the configuration returned when vendorid,servideid and modeid are passed in the query in one go without having to query 3 times separately.
Any other good approach for the above problem is also welcome.
You may want this:
where (VendorID, ServiceID, ModelID) = ($VendorID, $ServiceID, $ModelID) or
( (VendorID, ServiceID) = ($VendorID, $ServiceID) and ModelId is null) or
( VendorID = $VendorID and ServiceID is null and ModelId is null)
Alternatively you may want:
select t.*
from t
where VendorId = $VendorId and
(ServiceId = $ServiceId or ServiceId is null) and
(ModelId = $ModelId or ModelId is null)
order by ( ServiceId is not null ) desc,
( ModelId is not null ) desc
limit 1;
This returns one row with the best match.

MYSQL - COUNT() NULL Values

This has been racking my head. I've scoured the internet (including this place) and can't find a solution. So as a last resort I was hoping the good people of this forum might be able to help me out.
I have two tables:
TableA
Order_detailsID
OrderID
TitleID
Return_date
TableB
TitleID
Title_name
Quantity_in_stock
And would like to run a query that shows the remaining 'Quantity_in_stock'.
If the 'Return_date' is set to NULL then it means the item is currently out -- so I have been trying to use the count() function for the NULL values and subtract it from the 'Quantity_in_stock'.
This is the script I have so far:
DELIMITER //
CREATE PROCEDURE InStock()
BEGIN
Select TableB.TitleID,
TableB.Title_name,
TableB.Quantity_in_stock AS 'Total_Stock',
COUNT(TableA.return_date IS NULL) AS 'Rented_Out',
TableB.Quantity_in_stock - COUNT(TableA.return_date IS NULL) AS 'Remaining Stock'
From TableB
LEFT JOIN TableA
ON TableA.TitleID = TableB.TitleID
GROUP BY TableB.TitleID;
END//
This works if there is one of more of the TitleIDs at NULL, however if there are no values at NULL, then the Count() is still returning a value of 1 when it should be 0.
What am I doing wrong?
Instead of:
COUNT(TableA.return_date IS NULL)
use this:
SUM(CASE
WHEN TableA.TitleID IS NULL THEN 0
WHEN TableA.return_date IS NOT NULL THEN 0
ELSE 1
END)
The problem with the TableA.return_date IS NULL predicate is that it's true in two completely different situations:
When there is no matching record in TableA
When there is a matching record but TableA.return_date value of this exact record is NULL.
Using the CASE expression you can differentiate between these two cases.
I will like to mention a simple concept here, just keep counting the rows when that particular column is null.
select count(*) from table_name where column_name is null

No results even by using EXISTS

I don't undersand why MySQL returns "MySQL did not produce a record" whereas I use EXISTS (I willingly chose a subquery which doesn't produce records) :
SELECT page_ID
FROM ranks_update
WHERE EXISTS (
SELECT *
FROM ranks_update
WHERE ranking_ID = 3
AND current_rank = 1
AND rating_time < '2012-08-05 02:57:59'
AND rating_time >= '2012-08-05 00:00:00'
GROUP BY page_ID
);
By definition EXISTS allows to get a result from a query which doesn't return any records. Until now I've always got NULL in such case.
It is returning that message because no records match. NULL is a value for a column. It is quite different from an empty return set.
If you have an aggregate function, then the empty set returns a NULL. So the following would return a NULL value:
select max(Page_ID)
and this would return 0:
select count(Page_ID)

mysql return single result from single table with complex condition

I have this table :
table(fied1 int,field2 int,field3 varchar(40));
I would like to obtion without a stored procedure something like:
declare int nr default 0;
select coalesce(max(field1),0) into nr from table where field2=? and field3=?;
if(nr = 0) then
select coalesce(max(field1),0)+1 into nr from table;
end if;
i want the value of nr from single select.
pls help !!!
Only use the following query to get one plus to last inserted value in field1 column if no match found as per where clause else it returns the max value stored in field1:
This query is handling the case if there are no records in table.
the filter crieteria "and field1<>0" in following statement is required if field1 can have value 0 also otherwise remove this filter (and field1<>0) from following query
Select coalesce(
max(field1),
(select coalesce(max(field1),0)+1 from table)
)
from table where field2=? and field3=? and field1<>0;
I think this captures your requirements:
SELECT
CASE
WHEN (max(field1) IS NULL OR max(field1) = 0) AND field2=? AND field3=? THEN (max(field1)+1)
ELSE max(field1)
END AS `field1_max`
FROM table