Condition inside a Where clause in sql - sql

I have a stored procedure. In that where condition, I want to select the not null value if there are any, else select the null value from the table. Anyone Kindly help me..
ALTER PROCEDURE SearchPromotionBYPromotionANDVehicleID
#PromotionCode VARCHAR(100)
,#TypeId INT
,#LocationId INT
,#ClientId INT
AS
BEGIN
SET NOCOUNT ON;
SELECT top 1 tp.PromotionID
,tp.PromotionCode
,tp.ClientID
,tp.StartDate
,tp.EndDate
,tp.VehicleTypeId
,tv.VehicleType
,tp.LocationId
FROM tblstudent tp
LEFT OUTER JOIN tblType tv ON tp.TypeId = tv.TypeId
WHERE tp.PromotionCode = #PromotionCode
AND
( ( #LocationId IS NOT NULL AND tp.LocationId = #LocationId ) OR (tp.LocationId IS NULL) OR (#LocationId IS NULL) or (tp.LocationId = 0 ) )
In this consider 2 records (r1 and r2) with same promotion code and one with all locations (that is location id 0) and another with a location ID. When the parameter #locationId have a value(consider the value equal to the value of the record r2) then it have to return the record 2. Else have to return r1.

WHERE tp.PromotionCode = #PromotionCode
AND (( #LocationId IS NOT NULL AND tp.LocationId = #LocationId ) OR tp.LocationId IS NULL)
This condition selects those values where #LocationId has a not null and not 0 value, And the value needs to match with tp.LocationId, Otherwise it returns those where tp.LocationId is null.
Is it the result what you want? If you want different, let me know

Related

Using multiple nested OR statements in WHERE clause makes query return incorrect results

I have a WHERE clause that has a nested OR statement, as seen here:
-- Declaration of variables
DECLARE
#PageSize INT,
#PageNumber INT,
#SearchPhraseOne VARCHAR(20),
#SearchPhraseTwo VARCHAR(20),
#FilterCategory VARCHAR(30),
#FilterStatus TINYINT,
#NeedsFollowUp TINYINT,
#NeedsTraining TINYINT,
#NeedsInitialVacc TINYINT;
SET #PageNumber = 1;
SET #PageSize = 100;
SET #SearchPhraseOne = null;
SET #SearchPhraseTwo = null;
SET #FilterCategory = 'High Exposure';
SET #FilterStatus = null;
SET #NeedsFollowUp = 1;
SET #NeedsTraining = null;
SET #NeedsInitialVacc = null;
select * from(
select
vel.fullName,
vel.EecEmpNo,
vel.EecLocation,
vel.EecDateOfLastHire,
job.JbcDesc,
vei.eiInitialBBPDate,
vei.eiVCGivenDate,
iif(jv.verTypeName is null, 'Low Risk', jv.verTypeName) as vaccineCategory,
vel.eecEmplStatus,
count(distinct vh.vhID) as vaccCount,
max(isnull(vh.vhNextDateScheduled, null)) as maxNextDateScheduled,
max(cast(vh.vhSeriesComplete as int)) as seriesComplete,
iif(vel.eecEmplStatus = 'T', null,
coalesce(iif(max(cast(vh.vhSeriesComplete as int)) = 1, null, max(isnull(vh.vhNextDateScheduled, null))), -- check if the vaccine items have a SeriesComplete of 1, otherwise use NextDateScheduled
iif(vei.eiInitialBBPDate is not null, null, vel.EecDateOfLastHire), -- check if the InitialBBPDate is not null, if it isn't use DateOfLastHire
iif(vei.eiVCGivenDate is not null, null, vel.EecDateOfLastHire), null)) as actionDate -- check if the OrientationDate is not null, if it isn't use DateOfLastHire
-- if all three of these values are null then there's no ActionDate
-- Terminated employees will not have an action date assigned even if there's a match
from dbo.vaccEmpList vel
left join dbo.vaccEmployeeInfo vei on vei.eiEmployeeNo = vel.EecEmpNo
left join dbo.vaccVaccinationHistory vh on vh.vhEmployeeNo = vel.EecEmpNo
left join dbo.vaccVaccineTypeLookup vt on vh.vhVaccinationTypeID = vt.vtlVaccineTypeID and vt.vtIsActive = 1 -- Only get active vaccination types
join dbo.U_JobCode job on vel.EecJobCode = job.JbcJobCode
left join dbo.JobVerficationXref jv on vel.EecJobCode = jv.JobCode and jv.verName = 'Vaccination Category'
group by vel.fullName, vel.EecEmpNo, job.JbcDesc, jv.verTypeName, vel.EecLocation, vel.eecEmplStatus, vei.eiInitialBBPDate, vei.eiVCGivenDate, vel.EecDateOfLastHire
) as searchResults
where (
(
#SearchPhraseOne is null
or searchResults.fullName like #SearchPhraseOne + '%'
or searchResults.EecEmpNo = #SearchPhraseOne
)
and (
#SearchPhraseTwo is null
or searchResults.fullName like #SearchPhraseTwo + '%'
or searchResults.EecEmpNo = #SearchPhraseTwo
) -- Employee Name/ID
and (
#FilterStatus is null
or (searchResults.eecEmplStatus = 'A' or searchResults.eecEmplStatus = 'L')
) -- Employee Status
and (
#FilterCategory is null
or searchResults.vaccineCategory = #FilterCategory
) -- Employee Vaccination Category
and ( -- ISSUES OCCUR HERE
(#NeedsTraining is null
or (searchResults.actionDate is not null
and (searchResults.eiInitialBBPDate is null or searchResults.eiVCGivenDate is null))
) -- Needs Training if either of these two date values are null
or (#NeedsInitialVacc is null
or (searchResults.actionDate is not null
and (searchResults.vaccCount = 0))
-- Needs Initial Vaccination if there are no vaccine records
)
or (#NeedsFollowUp is null
or (searchResults.actionDate is not null
and ((searchResults.seriesComplete is null or searchResults.seriesComplete = 0) and searchResults.maxNextDateScheduled is not null))
-- Needs a follow-up date if no series complete was detected
)
)
)
The #NeedsFollowUp, #NeedsInitialVacc, and #NeedsTraining variables are all set by the variables above. When one or more of these are set to "1", the query should return employee entries that match the criteria inside their related statements. For example, if the "NeedsFollowUp" and "NeedsTraining" values are set to "1" then the query should return employees that need a follow-up or employees that need training.
Right now, when I set all three to "1" I receive the combined results I'm looking for, but if any of them are set to null, then the query doesn't return the correct results.
EDIT: Here's a reproducible example of what I'm seeing.
I think the way the clauses are set up is causing an issue, but I'm not really sure how to fix this. How can I get the OR statements to work in the way I described above?
I was able to make the OR clauses work correcting by switching from is null to is not null in my where clauses. Using the minimal example, it would look like this:
select * from AGENTS
where (
(#NeedsName is not null and AGENTS.AGENT_NAME is null)
or
(#NeedsCountry is not null and AGENTS.COUNTRY is null)
or
(#NeedsCountry is null and #NeedsName is null)
)
Be sure to include an additional clause for when all options are NULL, so that you can return the appropriate number of rows.
Here's a working version.

how to apply isnull to variable?

I have table called sample with columns:
Id, Name, Dept, active
Query:
select Id
from Sample
where Dept = #Dept and active = 1
I want to fetch id from sample table name by passing deptment name whose is active. There can come situation where where I get 2 records. Two dept might be active. That's why I am taking top 1. Some time might not come any record.
That's why I used like this in stored procedure:
declare #TempId int
set top 1 #TempId = Id
from Sample
where Dept = #Dept and active = 1
if(#TempId is null)
begin
#TempId = 0
end
Can I use isnull in the above select instead of after which is suitable for both my conditions?
No. First it must be select, not set.
And if select returns no rows, #TempId will not be changed. See this simple example
declare #TempId int = 0;
select #TempId = null where 1=2;
select #TempId;
I would write following code:
DECLARE #TempId int =
COALESCE((SELECT TOP 1 Id FROM [Sample] WHERE Dept = #dept AND Active=1), 0)
If no rows are returned, NULL coalescing function is used.
At the time of selecting record, check for the NULL value, and select the record which is NOT NULL.
declare #TempId int
select top 1 #TempId = Id from Sample where Dept = #Dept and active = 1 and Id is not null

Conditional Where Arguments in SQL Server

I have a table 'Asset' in database. This table has four fields (Id, Name, LocationId, CategoryId).
I want to make a stored procedure which will return the assets based on provided LocationId and CategoryId parameters.
I want to make Where clause optional with respect to LocationId i.e. If user passes LocationId as 0 then I dont want to put restriction on LocationId otherwise I need to put restriction on LocationId also. i.e If #LocationId is 0 then assets from all location ids should be returned.
How can I change following query to achieve this
select * from Asset where LocationId = #LocationId and CategoryId = #CategoryId
Any Help?
What you need to do is declare your variables as null at the beginning.
So #LocationID int = null
Then in your where clause you'll want to put something like
WHERE (LocationID = #LocationID or #LocationID IS NULL)
That way if you don't pass an ID, everything will be returned.
EDIT - So this works for you, just make the passing of the ID's optional instead of putting 0's in, you could of course do WHERE (LocationID = #LocationID or #LocationID = 0)
I just think the use of NULL's is much cleaner.
Full Query:
CREATE PROC
#LocationID int = 0,
#CategoryID int = 0
AS
SELECT *
FROM
Asset
WHERE
(LocationID = #LocationID or #LocationID = 0)
AND
(ActivityID = #ActivityID or #ActivtyID = 0)
You can use Case in your Where Clause
select * from Asset
where LocationId = Case When #LocationId=0 then LocationId else #LocationId end
and CategoryId = #CategoryId

IF ELSE condition in SQL select

I want to do a if-else condition statement in SQL Server but am not sure how.
Inside the stored procedure I have the following parameters:
#MarketId nvarchar (10),
#RegionId nvarchar (10)
And the following statement:
select * from Interaction I
where
(#MarketId = 0 ) OR (I.MarketId = (SELECT Id FROM Market WHERE ExternalId = #MarketId))
What I want to do is to check the value of #MarketId
if #MarketId = 0
then I want the where condition for I.MarketId to get its Ids from elsewhere like
(SELECT ID FROM Market WHERE ExternalId = #RegionId)
otherwise, if its 1, then I just want to leave it as is and get the Id from #MarketId instead of #RegionId..
How should I go about this?
Thanks!
This should work:
SELECT *
FROM Interaction I
WHERE ( #MarketID = 0
AND EXISTS (SELECT 1 FROM Market
WHERE ExternalId = #RegionId AND Id = I.MarketID)
OR I.MarketID = #MarketID

SQL WHERE ... IN clause with possibly null parameter

I am having some problems with my WHERE clause (using SQL 2008) . I have to create a stored procedure that returns a list of results based on 7 parameters, some of which may be null. The ones which are problematic are #elements, #categories and #edu_id. They can be a list of ids, or they can be null. You can see in my where clause that my particular code works if the parameters are not null. I'm not sure how to code the sql if they are null. The fields are INT in the database.
I hope my question is clear enough. Here is my query below.
BEGIN
DECLARE #elements nvarchar(30)
DECLARE #jobtype_id INT
DECLARE #edu_id nvarchar(30)
DECLARE #categories nvarchar(30)
DECLARE #full_part bit
DECLARE #in_demand bit
DECLARE #lang char(2)
SET #jobtype_id = null
SET #lang = 'en'
SET #full_part = null -- full = 1, part = 0
SET #elements = '1,2,3'
SET #categories = '1,2,3'
SET #edu_id = '3,4,5'
select
jobs.name_en,
parttime.fulltime_only,
jc.cat_id category,
je.element_id elem,
jt.name_en jobtype,
jobs.edu_id minEdu,
education.name_en edu
from jobs
left join job_categories jc
on (jobs.job_id = jc.job_id)
left join job_elements je
on (jobs.job_id = je.job_id)
left join job_type jt
on (jobs.jobtype_id = jt.jobtype_id)
left join education
on (jobs.edu_id = education.edu_id)
left join
(select job_id, case when (jobs.parttime_en IS NULL OR jobs.parttime_en = '') then 1 else 0 end fulltime_only from jobs) as parttime
on jobs.job_id = parttime.job_id
where [disabled] = 0
and jobs.jobtype_id = isnull(#jobtype_id,jobs.jobtype_id)
and fulltime_only = isnull(#full_part,fulltime_only)
-- each of the following clauses should be validated to see if the parameter is null
-- if it is, the clause should not be used, or the SELECT * FROM ListToInt... should be replaced by
-- the field evaluated: ie if #elements is null, je.element_id in (je.element_id)
and je.element_id IN (SELECT * FROM ListToInt(#elements,','))
and jc.cat_id IN (SELECT * FROM ListToInt(#categories,','))
and education.edu_id IN (SELECT * FROM ListToInt(#edu_id,','))
order by case when #lang='fr' then jobs.name_fr else jobs.name_en end;
END
Something like
and (#elements IS NULL OR je.element_id IN
(SELECT * FROM ListToInt(#elements,',')))
and (#categories IS NULL OR
jc.cat_id IN (SELECT * FROM ListToInt(#categories,',')))
....
should do the trick
je.element_id IN (SELECT * FROM ListToInt(#elements,',')) OR #elements IS NULL
that way for each one
Have you tried explicitly comparing to NULL?
and (#elements is null or je.element_id IN (SELECT * FROM ListToInt(#elements,','))
And so on.