Set blank result equal to specific string in SQL Server - sql

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.

Related

Case in Where Clause SQL (Oracle)

I want to filter a query in the Where Statement. I want to compare IDs with 'IN' but only if an input has value.
If this text comes empty I don't want to compare. Prevent the error query
EXAMPLE:
StringProductIDs = ''
WHERE
({Issue}.[ServiceRequestId] IN (#StringServiceRequestIDs))
AND ({ServiceRequest}.[Id] IN (#StringServiceRequestIDs))
AND ({Product}.[Id] IN (#StringProductIDs) OR #StringProductIDs = '') /* Is this one that i want to prevent*/
AND EXTRACT(MONTH FROM {Sprint}.[CompleteDate]) = #Month
AND EXTRACT(YEAR FROM {Sprint}.[CompleteDate]) = #Year
In this case, I just want to filter things.id if the value passed as a parameter has value. If it comes empty I don't want to compare and avoid the 'AND' line
Or try another approach:). There is a way to run a query only if this input has value? If it has no value, it returns nothing. If the input has value run normally –
Many thanks
You need OR :
WHERE (things.active = 1 AND things.state = 2) AND
(things.id IN (#INPUT) OR #INPUT IS NULL);

T-SQL concatenation issue with NULLS

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.

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.

db2 stored procedure if else variable comparison

I am trying to compare a variable in db 2 sp using like, however it always goes to the else part of the statement, can someone correct the syntax here..here is the part of the code
do
IF(#variable like '%abc') THEN
set #anotherVariable='abc';
ELSEIF (#variable like '%def') THEN
set #anotherVariable='def';
ELSEIF (#variable like '%def') THEN
set #anotherVariable='def';
ELSE
set #anotherVariable='xyz';
END IF;
END FOR;
This code is part of a cursor, query always returns 1 value, however my comparison is not working(incorrect syntax?), it always goes to the last else as if it never was able to match. I know that value is there but its not comparing in this manner...Thanks
Are you writing SQL-PL code? Because variables are referenced directly by its name, not preceded by the '#' sign.
Another thing is that you are using the like operator outside a query. 'Like' is not a function, it is a predicate: http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0000751.html
Instead, you can use a 'case' in the select and then return the corresponding value. In that way you do not need to do an 'if-else': http://pic.dhe.ibm.com/infocenter/db2luw/v10r5/topic/com.ibm.db2.luw.sql.ref.doc/doc/r0023458.html

Replacing a calculated field column with a Blank when a NULL is returned?

I'm doing a simple query that uses the DateDiff function to find the number of days between the dates. However, with regards to certain instances, I'd like to populate a blank field (not a null).
Something like this is what I currently have, and it seems to work fine (but it populates a null).
[Test (Years)] = CASE WHEN TYPE IN ('A','B')
THEN NULL ELSE IsNull(CONVERT(decimal(28,12),
(DATEDIFF(d,#StartDate,ExpirationDate)))/365,0) END
Now if I try something like this... which tries to convert all TYPE A and B to populate a blank, I'll get the following error message: Error converting data type varchar to numeric.
[Test (Years)] = CASE WHEN TYPE IN ('A','B')
THEN '' ELSE IsNull(CONVERT(decimal(28,12),
(DATEDIFF(d,#StartDate,ExpirationDate)))/365,0) END
Is there a simple thing I'm missing? I've tried doing the calcualtions without converting to a decimal, but it doesn't seem to work. Any ideas? Thanks
CASE is an expression that returns exactly one value and all of the branches must yield compatible types. A string (even a blank string) is not compatible with a decimal, so you need to do something like:
CASE WHEN ... THEN '' ELSE
CONVERT(VARCHAR(32), COALESCE(CONVERT(DECIMAL(23,12), ... ,0)) END
Note that this hack will only work if you are presenting the data to an end user. If you are trying to store this data in a column or use it in other calculations, it too will be tripped up by the blank string. A number can't be a blank string:
DECLARE #i INT = '';
SELECT #i;
Result:
0
So, if you don't want "empty" numerics to be interpreted as 0, stop being afraid of NULL and if you are dealing with this at presentation time, have the presentation layer present a blank string instead of NULL.