IF ELSE condition in SQL select - sql

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

Related

Condition inside a Where clause in 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

SQL query to retrieve data based on either emailid or userid

I have to write a query for a login page where the user can enter either emailid(varchar datatype) or userid(int datatype). How do I write a query for this without knowing the datatype of the input?
CREATE PROCEDURE my_stored_procedure
#emailId nvarchar(50) = NULL,
#userId int = NULL
AS
SET NOCOUNT ON;
IF (#emailId IS NOT NULL) AND (LEN(#emailId) > 0)
SELECT * FROM MYTABLE WHERE EmailId = #emailId
ELSE
SELECT * FROM MYTABLE WHERE UserId = #UserId
GO
Your input parameter should be of varchar type.
Then in your procedure use ISNUMERIC function to check for number. Have two queries based on that with IF statement in case if it is int or varchar.
DECLARE #userInput VARCHAR(50)
IF ISNUMERIC(#userInput) = 1
BEGIN
-- Your query with userid
END
ELSE
BEGIN
-- Your query with emailid
END
Try this query it may help you.
DECLARE #emailid varchar(250),#userid bigint
set #emailid='A'
SET #userid=3
select * from yourtable
where case when #emailid='A' THEN 'A' ELSE emailid END=#emailid
AND case when #userid=0 THEN 0 ELSE userid END=#userid
Note: You should pass 'A' as default value for email_id and 0 for userid or else you can pass your required input

Insert data if it does not exist

I want to insert some data in my column only if my query parameters are not already added.
For example, if my row contains :
a=4&b=7&c=9
and now, when update happens with : b=7&c=9, then i should not append it.
o/p:a=4&b=7&c=9
But if update happens with d=9&e=9
then it should append it.
o/p : a=4&b=7&c=9&d=9&e=9
My normal Update query is :
#AdditionalParams = 'b=7&c=9'
SELECT #id = mid FROM Table2 WHERE sid = #SId
AND cid = #CId;
UPDATE Table1
SET additional_params = CONCAT (
additional_params
,iif(additional_params IS NULL, NULL, '&')
,#AdditionalParams
)
WHERE mid = #id
How can i use here the NOT EXIST Clasue.
But with not exist clause it checks whole row, I just want to check if parameters exist, then dont insert it.
I guess you are looking for a not like clause
declare #AdditionalParams varchar(50) = 'b=7&c=8'
SELECT #id = mid
FROM Table2
WHERE sid = #SId
AND cid = #CId;
UPDATE Table1
SET additional_params = CONCAT (
additional_params
,iif(additional_params IS NULL, NULL, '&')
,#AdditionalParams
)
WHERE mid = #id
and additional_params not like '%'+ #AdditionalParams +'%';

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

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.