how can I have different where condition using case statement? - sql-server

#HistoryMSBType => This is a variable which can contain any varchar.
Depending upon it's value, i need to have different type of where clause.
How can I achieve this ?
SELECT * FROM stageTable map
WHERE id = 1
CASE #HistoryMSBType
WHEN 'Utilization Other' THEN
AND map.ColumnID = 4
WHEN 'Cost Other' THEN
AND map.ColumnID = 6
ELSE
AND map.ColumnName = #HistoryMSBType
END

SELECT *
FROM stageTable map
WHERE id = 1
AND (
(#HistoryMSBType = 'Utilization Other' AND map.ColumnID = 4)
OR
(#HistoryMSBType = 'Cost Other' AND map.ColumnID = 6)
OR
(isnull(#HistoryMSBType,'') NOT IN ('Utilization Other','Cost Other')
AND map.ColumnName = #HistoryMSBType)
)
You need the ISNULL to make it match the CASE-ELSE exactly, but it won't matter if it can never be null.

Related

Condition check in where clause based on parameter passed to stored procedure

The stored procedure I am working on has 2 parameters #IsApproved (BIT) and CustomId (INT).
Now in my WHERE clause I want to check if #IsApproved or not, if it is approved then use A.[FunctionalId] = #CustomId else A.[InstallId] = #CustomId.
I tried like this, but it throws an error.
SELECT
AppKeyId, AppName, AppVersion
FROM
dbo.[Application] A
WHERE
CASE
WHEN #IsApproved = 1 THEN A.[FunctionalId] = #CustomId
ELSE A.[InstallId] = #CustomId
END
A CASE expression returns a scalar value, not a boolean result; THEN A.[FunctionalId] = #CustomId isn't valid as it's not a scalar value.
Use an OR:
SELECT AppKeyId,
AppName,
AppVersion
FROM dbo.Application A
WHERE (#IsApproved = 1 AND A.[FunctionalId] = #CustomId)
OR (#IsApproved = 0 AND A.[InstallId] = #CustomId);

How to include IF ELSE in SQL Query

I am attempting to put an IF ELSE statement into the follow SQL Query, but it keeps breaking when I try to execute. I have never used IF ELSE in SQL so I am assuming I am not including it correctly
Query without IF ELSE
UPDATE RA SET
CreditInvoiceAmount = CSV.CreditInvoiceAmount,
CreditInvoiceDate = CSV.CreditInvoiceDate,
CreditInvoiceNumber = CSV.CreditInvoiceNumber,
CreditDeniedDate = CSV.CreditDeniedDate,
CreditDeniedReasonId = CSV.CreditDeniedReasonId,
CreditDeniedNotes = CSV.CreditDeniedNotes
FROM ReturnAuthorization RA
JOIN TemporaryCsvUpload CSV
on RA.Id = CSV.Id
IF ELSE
IF CSV.CreditInvoiceDate = null AND CSV.CreditDeniedDate != null THEN
StatusId = 7;
ELSE
StatusId = 8;
Insert Attempt
UPDATE RA SET
CreditInvoiceAmount = CSV.CreditInvoiceAmount,
CreditInvoiceDate = CSV.CreditInvoiceDate,
CreditInvoiceNumber = CSV.CreditInvoiceNumber,
CreditDeniedDate = CSV.CreditDeniedDate,
CreditDeniedReasonId = CSV.CreditDeniedReasonId,
CreditDeniedNotes = CSV.CreditDeniedNotes,
IF CSV.CreditInvoiceDate = null AND CSV.CreditDeniedDate != null THEN
StatusId = 7;
ELSE
StatusId = 8;
FROM ReturnAuthorization RA
JOIN TemporaryCsvUpload CSV
on RA.Id = CSV.Id
Any guidance on how to correctly put this if statement into the SQL block would be appreciated. Thanks!
Use a CASE expression to implement a IF logic based on which you determine what value to assign into a column for a specific row.
UPDATE RA
SET CreditInvoiceAmount = CSV.CreditInvoiceAmount
,CreditInvoiceDate = CSV.CreditInvoiceDate
,CreditInvoiceNumber = CSV.CreditInvoiceNumber
,CreditDeniedDate = CSV.CreditDeniedDate
,CreditDeniedReasonId = CSV.CreditDeniedReasonId
,CreditDeniedNotes = CSV.CreditDeniedNotes
,StatusId = CASE
WHEN CSV.CreditInvoiceDate IS NULL
AND CSV.CreditDeniedDate IS NOT NULL
THEN 7
ELSE 8
END
FROM ReturnAuthorization RA
INNER JOIN TemporaryCsvUpload CSV ON RA.Id = CSV.Id
CASE is valid for both SQL Server and MySQL, so it should work with either systems. Also, please consider editing your question and leaving only the relevant tag (what RDBMS you're actually using).
// You can try this
StatusId = IF ((CSV.CreditInvoiceDate IS NULL AND CSV.CreditDeniedDate IS NOT NULL), 7, 8)

Conditional WHERE clause to combine two queries

I have a large SELECT INTO statement in a T-SQL script and currently I have two separate SELECT INTO's only differing by one OR condition in the WHERE clause. If my variable #cycle_nbr = 1 I have it doing one SELECT INTO, if #cycle_nbr = 0 I have it doing the other SELECT INTO.
I was wondering if there was a way to do this in one SELECT INTO with the #cylce_nbr condition in the WHERE itself.
Here is my WHERE clause:
WHERE ((a.gl_indicator = '0' OR a.gl_indicator = '1')
AND (a.gl_ins_type = '1' OR a.gl_ins_type = '3' )
AND rel_file_nbr is NULL
AND a.alpha_line NOT LIKE '%Z'
AND mis_process_dt >= #start_dt
and acctg_cyc_ym = #acctg_cyc)
OR (a.prem_sys_cd='T' AND acctg_cyc_ym = #acctg_cyc )
I only want this last condition OR (a.prem_sys_cd='T' AND acctg_cyc_ym = #acctg_cyc ) in there if #cycle_nbr = 1. Can I put an IF in there somewhere to make this work? Or do I have to stick with the IF(#cycle_nbr = 1) run this select ELSE run the other select?
Include your variable in the OR statement, i.e.,
OR (a.prem_sys_cd='T' AND acctg_cyc_ym = #acctg_cyc AND #cycle_nbr = 1)

Optional Conditional statement in where clause

I need to add a condition in my WHERE clause that will include items in a search if #UserRoleId = 4, else exclude them from the search (SQL Server).
INSERT INTO #partData
(
PartPrefix,
PartNumber,
MyProDescription,
ItemNumber,
PartType,
Side,
VehicleLocation,
MyProPrice
)
SELECT
CASE
WHEN LEFT(myParts.MyProDescription, 4) = 'FOIL' THEN 'FOIL'
ELSE LEFT(myParts.PartNumber, 3)
END,
PartNumber,
MyProDescription,
ItemNumber,
PartType,
Side,
VehicleLocation,
MyProPrice
FROM
MyProExport myParts
WHERE
#year BETWEEN myParts.YearFrom AND myParts.YearTo AND
myParts.CarMake = #make AND
REPLACE(myParts.CarModel, ' ', '') = REPLACE(#model, ' ', '') AND
(
myParts.EngineDisplacement = #engine OR
myParts.EngineDisplacement = 'ALL'
) AND
LEFT(myParts.PartNumber, 3) NOT IN ('300','400') -- Exclude these parts if not #UserRoleId = 4
The last statement needs to be modified to display 300 and 400 only if #UserRoleId is = 4. Else just show 300. I’m confused on how to set this up. I’ve tried:
CASE
WHEN #UserRoleId = 4 THEN LEFT(myParts.Number, 3) NOT IN ('300','400') -- Exclude parts
with no luck...
Instead of a case statement, just use AND/OR logic.
AND (LEFT(myParts.HollanderNumber, 3) = '300'
OR (#UserRoleID = 4 AND LEFT(myParts.HollanderNumber, 3) = '400'))
This will always display 300 and only display 400 if the #UserRoleID = 4

How to get all values including null in a SQL Server case statement?

I have a big stored procedure, and basically I want to select all values (including null) if my variable #DimBrowserId is set to 0. I am using a case statement, however this is only catching values that actually have something and ignoring the NULL valued fields. Because I am using the = clause in the WHERE I cannot do IS NULL. I do not want to have to write 2 IF statements because the stored procedure would then be enormous, so I want to know how to get null values as well. Here is my code:
SELECT
DATEPART(yy, DATEADD(mi, #Mdelta, d.DimDateValue)),
DisableCount = COUNT(*)
FROM
dbo.FactDisable AS f
JOIN
dbo.DimDate AS d ON f.DimDateId = d.DimDateId
JOIN
dbo.DimDevice AS v ON f.DimDeviceId = v.DimDeviceId
WHERE
d.DimDateValue >= #StartDateGMT
AND d.DimDateValue <= #EndDateGMT
AND f.IsTest = #IncludeTest
AND f.DimProductId = #DimProductId
AND v.DimBrowserId = CASE
WHEN #DimBrowserId = 0 THEN v.DimBrowserId
ELSE #DimBrowserId
END
GROUP BY
DATEPART(yy, DATEADD(mi, #Mdelta, d.DimDateValue))
The code is near the CASE clause.
Thanks
Change that line to be
AND (#DimBrowserID = 0 OR #DimBrowserID = v.DimBrowserId)
If #DimBroserID is 0 then no filtering will be applied for this line.
Use ISNULL:
SELECT DATEPART(yy,DATEADD(mi,#Mdelta,d.DimDateValue)),
DisableCount=COUNT(*)
FROM dbo.FactDisable AS f
JOIN dbo.DimDate AS d ON f.DimDateId = d.DimDateId
JOIN dbo.DimDevice AS v ON f.DimDeviceId = v.DimDeviceId
WHERE d.DimDateValue >= #StartDateGMT AND d.DimDateValue <= #EndDateGMT
AND f.IsTest = #IncludeTest AND f.DimProductId = #DimProductId
AND v.DimBrowserId = CASE WHEN ISNULL(#DimBrowserId,0) = 0 THEN v.DimBrowserId ELSE #DimBrowserId END
GROUP BY DATEPART(yy,DATEADD(mi,#Mdelta,d.DimDateValue))
CASE WHEN COALESCE(#MightBeNull, 0) = 0 THEN ZeroResult ...
will be treated as zero if #MightBeNull is null, and whatever #MightBeNull is if it's not null.
Assuming null means any browser, a better data model for this scenario might be to set an ID that identifies any browser, instead of setting it to null.
You probably know what you are running into is NULL does not equal NULL in a comparison.
Assuming you don't have control of the data model to fix that, one option would be to coalesce your NULL values to an unused id.
The resulting WHERE clause would look like this, assuming -1 is the unused value you choose.
AND COALESCE(v.DimBrowserId, -1) = CASE WHEN #DimBrowserId = 0 THEN COALESCE(v.DimBrowserId, -1) ELSE #DimBrowserId END

Resources