T-SQL concatenation issue with NULLS - sql

I'm trying to do a simple concatenation but failing somewhere! I want to display the Note in the email only if the other two variables are not empty. Even if one variable contains data it should display the Note. Below is my code.
SET #Note = CASE
WHEN #tableHTML_AssignedTo IS NOT NULL OR #tableHTML_SubmittedBy IS NOT NULL
THEN 'Note: The tickets with the following statuses are not listed in this alert: Closed,Rejected'
ELSE NULL
END
SET #ComposeBody = ISNULL(#tableHTML_AssignedTo, '') +
ISNULL(#tableHTML_SubmittedBy, '') +
ISNULL(#Note, '')
I know it's simple code but it's not obvious to my mind what I'm doing wrong. But with my code, an empty email is sent if both the tables are empty with Notes. If I remove Notes, no email is sent but I want to add the Notes in the email
Note: I'm executing this code inside cursor to send emails recursively

I'd do it like this -- seems simpler.
The trick here is to understand how null works with concat. Anything concat with null is null. So the first parameter to COALESCE will be null if Assigned or submitted is null. Each next step checks the other two cases.
SET #Note = 'Note: The tickets with the following statuses are not listed in this alert: Closed,Rejected';
SET #ComposeBody = COALESCE(
#tableHTML_AssignedTo+#tableHTML_SubmittedBy+#Note, -- Selected if both non null
#tableHTML_AssignedTo+#Note, -- Selected if SubmittedBy null
#tableHTML_SubmittedBy+#Note) -- Selected if AssignedTo null
-- Both are null, set body to null.

Related

How to replace nulls in entire sheet without knowing which column will have null values

Several times a month I append data from excel to our database using Microsoft Access. Right now I have update queries that look for nulls in columns that commonly have them and replaces them with empty strings.
UPDATE example_excel_sheet SET example_excel_sheet.trouble_column_1 = '',
example_excel_sheet.trouble_column_2 = '', example_excel_sheet.trouble_column_3 = '',
WHERE (((example_excel_sheet.trouble_column_1)='' Or (example_excel_sheet.trouble_column_1)
Is Null) AND ((example_excel_sheet.trouble_column_2)='' Or (example_excel_sheet.trouble_column_2) Is
Null) AND ((example_excel_sheet.trouble_column_3)='' Or
(example_excel_sheet.trouble_column_3) Is Null));
There are 2 problems with this solution
This query only updates if all three trouble columns are either null or blank
The columns that might be null are sometimes unpredictable, there might be 5 null fields instead of 3 so I'll have to do the extra 2 manually.
Please tell me there is a better way to do this?
Could use Nz() then it is irrelevant if field is Null or not. Eliminate WHERE clause and run update on every record. Include all columns that might need update.
UPDATE example_excel_sheet SET trouble_column_1 = Nz(trouble_column_1,''), trouble_column_2 = Nz(trouble_column_2),''), trouble_column_3 = Nz(trouble_column_3),''), trouble_column_4 = Nz(trouble_column_4),''), trouble_column_5 = Nz(trouble_column_5),'')
Or to avoid calling that VBA function use IIf and IS NULL
trouble_column_1 = IIf(trouble_column_1 IS NULL, '', trouble_column_1)
Or use VBA and run 5 separate SQL action statements.

How to set a NULL when entering NULL keeps the old value

I have a stored procedure where it is able to update the 4 columns below as there are 4 parameters (1 parameter for each column with ClawbackID the only one that doesn't change).
Now there is no fixed amount of columns that can be updated, I may choose to update 1 column, or 3 columns or all 4 columns. So to reduce human error, I have a coalesce so that if the user enters in 'NULL' for a particular parameter whilst executing a procedure, the original amount stays.
Example for row 3 for 'ClawbackAmount', if I enter in NULL and execute, it will still display the 'ClawbackAmount' 900.54. Now the problem I have is that actually want to set this amount to 'NULL', but I don't want to lose the functionality that if I type in 'NULL' when executing my procedure that it keeps the old value.
My question is that is there a way or an idea you can think of where I type in NULL then the default values stays but if I type in something like '' then it will default to 'NULL'?
Or alternatively type in the word 'SAME' to keep the default value and then type in 'NULL' for a null value? Just ideas really to get around it?
Below is the code I have with the parameters included as they begin with #:
update clw
set clw.PaymentID = Coalesce(#PaymentID, clw.PaymentId)
,clw.ClawbackDate = Coalesce(#ClawbackDate, clw.ClawbackDate)
, clw.ClawbackPercent = Coalesce(#ClawbackPercent, clw.ClawbackPercent)
, clw.ClawbackAmount = Coalesce(#ClawbackAmount,clw.ClawbackAmount)
OUTPUT '[Fees].EBD.Clawback' 'TableName','ClawbackId', inserted.ClawbackId,
Core.updXMLFragment('PaymentId', inserted.PaymentId, deleted.PaymentId) +
Core.updXMLFragment('ClawbackDate', Convert(varchar(50),inserted.ClawbackDate, 112), Convert(varchar(50),deleted.ClawbackDate, 112)) +
Core.updXMLFragment('ClawbackPercent', inserted.ClawbackPercent, deleted.ClawbackPercent) +
Core.updXMLFragment('ClawbackAmount', inserted.ClawbackAmount, deleted.ClawbackAmount)
INTO #OutputList
from [Fees].EBD.Clawback clw
Where
ClawbackId = #ClawbackID
Below is the code for the execution as an example for row 3 if I want to make the desired change:
First Param is ClawbackID (this doesn't change but need it to know which row to manipulate.
Second Param is PaymentID which is NULL as want to keep the same
Third Param is Clawbackdate which is NULL as want to keep the same
Fourth Param is ClawbackPercent which needs to be 0.25
Last Param is ClawbackAmount which I need to set to NULL. This is an int field btw but leaving it NULL will keep the orginal amount displayed.
exec SupportAudit.BI.UpdateHotelClawback 28817, NULL, NULL, 0.25, NULL
I generally use some specific invalid value as an indicator the column should be set to NULL. In the case of ClawbackPercent and ClawbackAmount, -1 seems like a good candidate. The change would look like this:
...
, clw.ClawbackPercent = NullIf(Coalesce(#ClawbackPercent, clw.ClawbackPercent), -1)
, clw.ClawbackAmount = NullIf(Coalesce(#ClawbackAmount,clw.ClawbackAmount), -1)
...
For string parameters, '' (the empty string) might be an appropriate choice.

Oracle : IN and OR

I've a scenrio which process many data in Oracle database. In some cases, the variable Sec_email will contain many values and in some cases Sec_email will contain null or ' '.
so can please any one tell me how to write a query for this?
I tried with
(C.SECONDARY_EMAIL IN ('?,?') OR '' = '' )
where C is the Client table.
When I use this i get the count as 0.
You can perform a not null check before the IN comparison like
Sec_email is not null and C.SECONDARY_EMAIL IN (...
One obvious problem is that Oracle (by default) treats empty strings as NULL. So: '' = '' is the same as NULL = NULL, which is never true.
Arrgh.
In any case, you are probably constructing the query, so use is null instead:
(C.SECONDARY_EMAIL IN ('?,?') OR '' IS NULL
I think the real problem, though, is the first comparison. The IN list has one element with a constant, not two (but perhaps that is your intention). If you want to put a variable number of values for comparison, one method uses regular expressions. For instance:
C.SECONDARY_EMAIL REGEXP_LIKE '^val1|val2|val3$' or '' IS NULL
If you would like to get a list of values when some of them is null you should use:
("some other conditions" OR C.SECONDARY_EMAIL IS NULL)
The question is if it is not null and not ' ' value what you are expecting, if it should be some king of
pattern you should use regular expression:
regexp_like(C.SECONDARY_EMAIL, '^(.+?[,]+?)+$')
Also, if you have a few conditions in where clause use should use brackets to group you conditions null check and another one.
All conditions i this case will be divided by OR.
(C.SECONDARY_EMAIL IS NULL OR regexp_like(C.SECONDARY_EMAIL, '^(.+?[,]+?)+$'))
or
(C.SECONDARY_EMAIL IS NULL OR regexp_like(C.SECONDARY_EMAIL, '^(.+?[,]+?)+$')
OR C.SECONDARY_EMAIL = ' ')

Set blank result equal to specific string in SQL Server

I have a query that returns a result set which contains a certain column that needs some tweaking. Basically, in the result set, there are certain rows that contain a blank value for the applicable column. What I need to do is set all instances of that blank value to a specific string. I have tried declaring a variable and setting the variable equal to the column name (using a SELECT statement) and then using an IF statement to set the value to a specific string if it is blank (' '). My code thus far is as follows:
declare #sourceNode varchar(30)
set #sourceNode = (select sn_name from pt_cust)
if #sourceNode = '' begin
set #sourceNode = 'None'
end
This code returns an error stating that the sub-query returns more than 1 value. This seems like an easy task but I am stuck at the moment. How can this be accomplished?
This is a case (heh) for CASE:
SELECT CASE WHEN sn_name = '' THEN 'None' ELSE sn_name END
FROM pt_cust
You are getting the error message you mentioned because your SELECT statement can return more than one row, in which case it can not be assigned to a variable.

how can I replace blank value with zero in MS-Acess

I have below query in Ms-Access but I want to replace Blank value with zero but I can't get proper answer. Is there any way to replace blank value in zero.
(SELECT
SUM(IIF(Review.TotalPrincipalPayments,0,Review.TotalPrincipalPayments))+
SUM(IIF(Review.TotalInterestPayments,0,Review.TotalInterestPayments ))
FROM
tblReviewScalars as Review
INNER JOIN tblReportVectors AS Report ON(Review.LoanID=Report.LoanID)
WHERE Report.AP_Indicator="A" AND Report.CashFlowDate=#6/5/2011# AND Review.AsofDate=#6/5/2011# AND ( Review.CreditRating =ReviewMain.CreditRating)) AS [Cash Collected During the Period],
I assume TotalPrincipalPayments and TotalInterestPayments are both numeric types, hence the 'blanks' in question is the NULL value.
In SQL, the set function SUM will disregard NULL values, unless all values resolve to NULL in which case NULL is returned (erroneously and the error is with SQL not Access for a change :)
To use a simple example, SELECT SUM(a) FROM T; will only return NULL when a IS NULL is TRUE for all rows of T or when T is empty. Therefore, you can move the 'replace NULL with zero' logic outside of the SUM() function. Noting that "NULLs propagate" in calculations, you will need to handle NULL for each SUM().
You haven't posted the whole of your query e.g. the source of the correlation name ('table alias') ReviewMain is not showm. But it seems clear you are constructing a derived table named "Cash Collected During the Period", in which case your calculated column needs an AS clause ('column alias') such as TotalPayments e.g.
...
(
SELECT IIF(SUM(Review.TotalPrincipalPayments) IS NULL, 0, SUM(Review.TotalPrincipalPayments))
+ IIF(SUM(Review.TotalInterestPayments) IS NULL, 0, SUM(Review.TotalInterestPayments))
AS TotalPayments
FROM tblReviewScalars as Review
INNER JOIN tblReportVectors AS Report
ON Review.LoanID = Report.LoanID
WHERE Report.AP_Indicator = 'A'
AND Report.CashFlowDate = #2011-05-06#
AND Review.AsofDate = #2011-05-06#
AND Review.CreditRating = ReviewMain.CreditRating
) AS [Cash Collected During the Period], ...
An alternative to #onedaywhen's answer is to use the nz function, which is specifically for null-substitution:
SELECT
SUM(NZ(Review.TotalPrincipalPayments,0))+
SUM(NZ(Review.TotalInterestPayments,0))
...
As onedaywhen pointed out, this is functionally equivalent to putting the function outside the aggregate, which may perform better (the function is called once, rather than once per un-aggregated row):
SELECT
NZ(SUM(Review.TotalPrincipalPayments),0)+
NZ(SUM(Review.TotalInterestPayments),0)
...
To change a null value to a zero in an Access 2010 database, open your table, go to design view, click on the field and set the default value to: =0.