How to include IF ELSE in SQL Query - sql-server

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)

Related

SQL Query for list within select where field = value and otherfield = othervalue

I need to fudge an existing SQL Server procedure rather quickly. It's a bit of a hack job but needs must.
I need for the following to return a list of voucher codes and invoice numbers rather than just one row of data where the comment is (in the WHERE clause):
SELECT TOP 10
IH.INH_Voucher AS [ID], IH.COY_ID AS COY_ID,
IH.INH_DateSupInv AS ORD_UpdatedOn,
V.VES_ID, V.VES_IMOnumber, IH.INH_Order,
IH.INH_ID AS ORD_ID, IH.INH_INDID
FROM
InvoiceHDR IH (NOLOCK)
INNER JOIN
VESSACCOMP VA ON IH.COY_ID = VA.COY_ID
INNER JOIN
Vessel V ON VA.VES_ID = V.VES_ID
WHERE
v.VSS_ID IN ('01') AND
(IH.INH_Status >= 20 AND IH.INH_Status <= 40) AND
--IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532' NEED LIST
IH.INH_INDID IS NOT NULL
So I would need
Voucher = '1700CH' AND SupInv = '1235' AND
Voucher = '180CH' AND SupInv = '1111' AND
And so on for many matching VoucherCodes and InvoiceCodes.
I hope this is clear?
Thanks.
You can apply the following WHERE clause to your query:::
WHERE
v.VSS_ID IN ('01') AND
(IH.INH_Status BETWEEN 20 AND 40) AND
((IH.INH_Voucher = '170CH' AND IH.INH_SupInv = '1532')
OR (IH.INH_Voucher = '180CH' AND IH.INH_SupInv = '1111'))
AND IH.INH_INDID IS NOT NULL

Query conversion from sybase to SQL Server

I have one query that is to convert from sybase to SQL server, I think we just need to change join operations.. Here is part of the query:
Can someone help me here?
FROM sy_trcr_divided d, fd_income_trans t
WHERE d.fd_id_income is not null
AND t.fd_income_transfer_id = d.fd_proc_id
AND t.fd_income_est_yn = 'Y'
AND d.fd_id_income = a.fd_id
AND d.fd_dist_to_i_or_p = 'A'
AND d.gl_year = :p_lYear
AND d.gl_period = :p_lPeriod
AND d.fd_include_stip_yn = 'Y'),0) AS ADDTO_FUND
FROM sy_est_income_detail a,
fd_master
WHERE a.fd_id *= fd_master.fd_id and
a.hr_id = :p_szHRID
My thought: have to replace *= with a join.
The *= should be a left join and the piece of the query you provided should probably be:
FROM sy_trcr_divided d
INNER JOIN fd_income_trans t ON t.fd_income_transfer_id = d.fd_proc_id
WHERE d.fd_id_income is not null
AND t.fd_income_est_yn = 'Y'
AND d.fd_id_income = a.fd_id
AND d.fd_dist_to_i_or_p = 'A'
AND d.gl_year = :p_lYear
AND d.gl_period = :p_lPeriod
AND d.fd_include_stip_yn = 'Y'),0) AS ADDTO_FUND
FROM sy_est_income_detail a
LEFT JOIN fd_master ON a.fd_id = fd_master.fd_id
WHERE a.hr_id = :p_szHRID

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

Not sure how to approch this, doing some math with error checking and updating my new value in tsql

if (freightCostTotal == 0)
{
freightCount = 1;
dataGridView1.Rows[i].Cells[iFreightCount].Value = "1";
if (freightCostDefinedTotal != 0)
{
freightCostTotal = Convert.ToDecimal(pcsg.Freight_CountColumn.Table.Rows[0]["Fixed Freight"].ToString());
}
else
{
if (!String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[iCost_Prior_ReCompute].Value.ToString()))
Cost_Prior_ReCompute = Convert.ToDecimal(dataGridView1.Rows[i].Cells[iCost_Prior_ReCompute].Value.ToString());
//freightCostPercentTotal = 0.05M;
//decimal costFreight = Convert.ToDecimal(pcsg.Freight_CountColumn.Table.Rows[0]["Cost"].ToString());
freightCostTotal = (Cost_Prior_ReCompute * freight_perc_);
}
dataGridView1.Rows[i].Cells[iFreight].Value = String.Format("{0:0.00}", freightCostTotal);
}
The following is not working. This is my first attempt at doing sql math
select freightCostTotal, Cost_Prior_ReCompute],freight_perc_, FixedFreight,
if (freightCostTotal == 0) then freightCount = 1;
if (freightCostDefinedTotal != 0) then freightCostDefinedTotal = FixedFreight else
set freightCostTotal = (Cost_Prior_ReCompute * freight_perc_);
from VF_CasINV_Cost
Thanks,
Jerry
Not sure what you're after exactly, but here's a start below. FYI -- your conditional on Cost_Prior_Recompute needs a default / else value -- I just put a '?' in there for now, since I can't tell what it should be.
Also -- I can't tell if freigntCostTotal is an actually field in your database that you're trying to update, or if you plan to just compute it based on other fields each time. So far, I'm assuming you're just going to compute it.
So this is how you would select -- keeping in mind (I assume from reading your code) you are looking for data where the frieghtCostTotal has NOT been updated in the database yet.
SELECT
1 as freightCount,
CASE WHEN freightCostDefinedTotal <> 0
THEN FixedFreight
ELSE ISNULL(Cost_Prior_ReCompute,?) * freight_perc_
END as freigntCostTotal,
Cost_Prior_ReCompute,
freight_perc_,
FixedFreight
FROM
VF_CasINV_Cost
WHERE
freightCostTotal = 0
Alternatively, you could just pull the data out like this, but it will get all data, not just the freightCostTotal = 0 data.
SELECT
1 as freightCount,
freigntCostTotal,
Cost_Prior_ReCompute,
freight_perc_,
FixedFreight
FROM
VF_CasINV_Cost
Here's how you would update. BTW -- If you're new to updating with SQL, I'd highly recommend you test this out on some non-production data first. Or at least, back-up your table first.
UPDATE VF_CasINV_Cost
SET freightCostTotal = CASE WHEN freightCostDefinedTotal <> 0
THEN FixedFreight
ELSE ISNULL(Cost_Prior_ReCompute,?) * freight_perc_
END
WHERE freightCostTotal = 0

how can I have different where condition using case statement?

#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.

Resources