In MySQL stored procedures check if a local variable is null - mysql

With the following example stored procedure
DECLARE Variable DOUBLE;
DECLARE Variable2 DOUBLE;
SELECT Something FROM Somewhere INTO Variable;
SELECT Something FROM SomewhereElse INTO Variable 2;
SELECT (Variable + Variable2);
If either Variable or Variable2 are NULL then the final SELECT will return null, what I would like is that if they are null they should be converted into 0.00 before the final SELECT, how do you do this? I already tried adding
SELECT 0.00 INTO Variable WHERE Variable IS NULL;
just above the final select but that didn't work.

SELECT COALESCE(variable, 0) + COALESCE(variable2, 0)

if you want each variable null converted to 0 use the solution posted by Quassnoi
SELECT COALESCE(variable, 0) + COALESCE(variable2, 0)
if you want to have 0 if either variable is null then use
SELECT COALESCE(variable + variable2, 0)

Quassnoi's correct, but it's even simpler (and a bit faster) to just coalesce the result:
SELECT coalesce( Variable + Variable2, 0 );
This works because for almost all operators, any null operand will make the operation null:
select 1 + null ; -- null
select null + 1 ; -- null
select null + null ; -- null
In the expression: SELECT coalesce( Variable + Variable2, 0 ); the result of the addition expression Variable + Variable2 is coalesce first argument; if that's null, coalesce returns its second argument, 0, otherwise it returns the (non-null) value of its first argument, which is the sum we want.
The few operators and functions that don't return null for a null operand are those designed to work on nulls: coalesce, is null, is not null.
As kristof notes below, the value of the select expression is different using Quassnoi's expression, if only one variable is null: his will return the value of the non-null variable if one is null; mine will return zero if either variable is null. Which is "right" depends on your intent.

Related

Unexpected BLOB results with MySQL testing NULL variable with IFNULL, COALESCE

In trying to test whether a variable has been defined, I discovered that the IF, IFNULL, and COALESCE statements return simply BLOB rather than the value I expected when (a) the variable has not been defined or (b) it has been explicitly set to NULL before being assigned a value in the session. I've verified this in MySQL versions 5.7 and 8.0.
SELECT IF(#p IS NULL, 'is null', 'not null'); # 'is null'
SELECT IF(#p IS NULL, 'is null', #p); # BLOB
SELECT IFNULL(#p, 'is null'); # BLOB
SELECT COALESCE(#p, 'is null'); # BLOB
The first statement acts as I expected, but the others return BLOB rather than 'is null'. The behavior is the same if preceded by SET #p = NULL.
On the other hand, if you do any of these, the above statements will all return 'is null', that is, they act as expected with a null value.
SET #p = NULL + 1 rather than SET #p = NULL before testing.
SET #p = 5; SET #p = NULL; That is, first set a non-null value, then set to null
SELECT COALESCE(#p+1, 'is null') # use expression #p+1 instead of #p.
Presumably, these three somehow set a type for NULL. In any case, an undefined variable or variable only defined as NULL have a different kind of NULL than those with a history of typing (?).
What is the underlying principle that explains this behavior? Is it simply an untyped NULL acts differently than a typed NULL, and those statements don't work with untyped ones?
Note: I know that that a workaround for this in a procedure, in order to detect undefined variables, can be
IF #p IS NULL
SET #p = default_value
END IF;
and it looks as if I can also use COALESCE(#p+1,default_value). But I'm interested in the explanation for why this is needed. Thanks.

Concat NULL with Varchar SQL Server 2008

I would like to ask how can I concatenate a nvarchar column with NULL without getting NULL? I would like to create an INSERT script using SELECT, but when any of the values is NULL, I get only NULL.
SELECT TOP 10
'IF NOT EXISTS(SELECT 1 FROM tblParameterKey
WHERE keyNames='''
+ CAST(ISNULL([keyNames], 'NULL') AS NVARCHAR(255)) + ''')
BEGIN
INSERT INTO tblParameterKey VALUES(''' + CAST(ISNULL([keyNames], 'NULL') AS NVARCHAR(255))+''')
END'
FROM tblParameterKey
This query returns correct insert inly when value is not null. If value is null it returns insert with 'NULL' which is not correct because it will be inserted as varchar and not as null value. If I remove ' ' the whole result will become null.
Edit - Maybe put the NULLIF statement inside the query string that way it will be null instead of string null.
SELECT TOP 10
'IF NOT EXISTS(SELECT 1 FROM tblParameterKey
WHERE keyNames=NULLIF('''
+ [keyNames] + ''', 'NULL') AS NVARCHAR(255))
BEGIN
INSERT INTO tblParameterKey VALUES(NULLIF(''' + [keyNames]+''', 'NULL') AS NVARCHAR(255))
END'
FROM tblParameterKey

MySQL Formating Strings or Returning Empty string on NULL

I am exporting a SELECT result to CSV via INTO OUTFILE. I have a series of simple SQL string functions I use to format the data. For instance: CONCAT('$',FORMAT(property.price,2)). I would like to otherwise return an empty string if the value is NULL, but I am unsure how to do both at the same time.
Also I am wondering the easiest way to take a TinyInt value of 0 or 1 and return "yes" or "no".
For tinyint you can use IF operator
select if(tinyint_value,'yes','no')
for first part you also can use if operator
select if(property.price is not null, CONCAT('$',FORMAT(property.price,2)),'')
To return yes, no or empty string depending on he value of the column you can use case as so:
select case column when 1 then 'Yes' else 'No' end as columalias ,
case when stringcolumn is NULL then '' else stringcolumn end as stringcolumn
from table
or
select case column when 1 then 'Yes' else 'No' end as columalias ,
IFNULL(stringcolumn,'') as stringcolumn
from table
You can use the coalesce() function. It returns the first of its arguments that's not NULL.
SELECT COALESCE(NULL, 1);
-> 1
SELECT COALESCE(2, 1);
-> 2

blank instead of zero

Duration = isnull(FunctionA(DateA,DateB),'')
The Function above calculates number of days and if day is null it displays
the value 0 instead of blank value
How can I change the above code to so that it shows blank and not 0 for value null?
If your function returns an integer the result from isnull will also be an integer. In the case the return value is null you will have an implicit conversion to integer for '' and that will be 0.
Try this:
declare #xx int
select isnull(#xx,'')
Result:
-----------
0
You can have the space if you first cast the return value from your function to varchar.
declare #xx int
select isnull(cast(#xx as varchar(10)),'')
Result:
----------
.
If your function returns 0 instead of null you can use nullif to get a null value before you cast to varchar.
declare #xx int = 0
select isnull(cast(nullif(#xx, 0) as varchar(10)),'')
Summary:
You need this:
Duration = isnull(cast(FunctionA(DateA,DateB) as varchar(10)),'')
or this
Duration = isnull(cast(nullif(FunctionA(DateA,DateB), 0) as varchar(10)),'')
If Duration is datatype int then you can't change that to an empty string (blank). You'll either have to change that to a string datatype (varchar for instance) or be okay with 0. int can either be NULL (if it is allowed) or a valid integer value. A blank string is not a valid integer value.
I use case statements and casting to do this.
Example:
case when columnX <> 0 then cast(columnX as nvarchar) else '' end
Basically, you're changing your numeric to show either as a character or a blank. You will have to do all your math before you change to nvarchar though, because outside of this, it becomes a string. It would be helpful if BLANK was a command and worked with numeric values though.
Hope this helps someone.
Is FunctionA returning 0 instead of null? The code you've written may be ok, but if FunctionA never returns null then...
You could declare Duration as a sql_variant datatype and allow implicit conversion to occur
so something like this should work
declare #DURATION sql_variant
select COALESCE(#DURATION, '')
set #DURATION=1
select COALESCE(#DURATION, '')

how to calculate within a procedure by the result of two queries

I have a Table called TblOrders.the fields are FldSlNo, FldStrategyID, FldTradeServerName, FldBaseDir, FldBinaryStartTime, FldInstrumentID, FldOrderNumber, FldBuySell, FldDisplayQuantity, FldRemainingQuantity, FldTotalTradeQuantity, FldLastTradePrice, FldLastTradeQuantity, FldPrice, FldOrderTime, FldReferenceText and FldOrderStatusID. Now I have a procedure called ProfitCalculation.
the procedure is given below:
delimiter //
CREATE PROCEDURE ProfitCalculation
(
IN instrument INT(20) ,
OUT profit float(10,2)
)
BEGIN
DECLARE buy DECIMAL(10,2);
DECLARE sell DECIMAL(10,2);
DECLARE oprofit DECIMAL(8,2);
SELECT SUM(FldLastTradeQuantity*FldPrice)
FROM TblOrders
WHERE FldInstrumentID = instrument AND FldBuySell = 'b' AND FldLastTradePrice != 0 AND FldLastTradeQuantity != 0 group by FldInstrumentID INTO buy;
SELECT SUM(FldLastTradeQuantity*FldPrice)
FROM TblOrders
WHERE FldInstrumentID = instrument AND FldBuySell = 's' AND FldLastTradePrice != 0 AND FldLastTradeQuantity != 0 group by FldInstrumentID INTO sell;
SELECT (sell-buy) INTO oprofit;
SELECT oprofit INTO profit;
END
//
delimiter ;
It always return null.
Is there have any solution for this problem.
Please help me out..
Thanks in advance
First, on both of the queries, you're specifying a GROUP BY, but expecting a single result. Since you're already including the grouped field in the where clause, this is not necessary.
Secondly, try running the individual statements (without the 'INTO' statement) - my guess is that at least one of them is returning NULL, causing the output to be null. If you would prefer zero to NULL as an output with an empty recordset, wrap the SUM() statement in COALESCE, as in:
SELECT COALESCE(SUM(FldLastTradeQuantity*FldPrice), 0)
This way, if one of the two statements return NULL, the other one will still work.
Specifying the conditions FldLastTradePrice != 0 AND FldLastTradeQuantity != 0 are unnecessary, as they'd be handled within the SUM statement.