Mysql Query to Stored Procedure - mysql

i have got access to a view of a datatable (mysql 8) which has the following values:
Values DB
now I tried to write an mysql query to fill up the Null values with the last value, because our visualisation tool cannot use null values and the lines in the graph will disappear.
SELECT UTCTIME,
case when Flammtemperatur1 is NULL then
#vorheriger_wert_Flammtemperatur1
else
#vorheriger_wert_Flammtemperatur1 := Flammtemperatur1
end as Flammtemperatur_1,
case when Flammtemperatur2 is NULL then
#vorheriger_wert_Flammtemperatur2
else
#vorheriger_wert_Flammtemperatur2 := Flammtemperatur2
end as Flammtemperatur_2,
case when Rauchgasventilator is NULL then
#vorheriger_wert_Rauchgasventilator
else
#vorheriger_wert_Rauchgasventilator := Rauchgasventilator
end as Rauchgasventilator_,
case when Rezirkulation is NULL then
#vorheriger_wert_Rezirkulation
else
#vorheriger_wert_Rezirkulation := Rezirkulation
end as FRezirkulation_
FROM pivot_test
order by utctime asc
That works fine, but i need to save this in a view or stored procedure, so that our tool can have access to it. Views are not possible because of the session variables.
Can someone please help me creating a Stored procedure for my problem? I have never written a SP before.
Thanks!
Result

CREATE PROCEDURE XXXXXName #Flammtemperatur1 DECIMAL (3,2), #Flammtemperatur2 DECIMAL (3,2)
, #Rauchgasventilator DECIMAL (3,2) ,#Rezirkulation DECIMAL (3,2)
AS
SELECT UTCTIME,
case when Flammtemperatur1 is NULL then
#vorheriger_wert_Flammtemperatur1
else
#vorheriger_wert_Flammtemperatur1 := Flammtemperatur1
end as Flammtemperatur_1,
case when Flammtemperatur2 is NULL then
#vorheriger_wert_Flammtemperatur2
else
#vorheriger_wert_Flammtemperatur2 := Flammtemperatur2
end as Flammtemperatur_2,
case when Rauchgasventilator is NULL then
#vorheriger_wert_Rauchgasventilator
else
#vorheriger_wert_Rauchgasventilator := Rauchgasventilator
end as Rauchgasventilator_,
case when Rezirkulation is NULL then
#vorheriger_wert_Rezirkulation
else
#vorheriger_wert_Rezirkulation := Rezirkulation
end as FRezirkulation_
FROM pivot_test
order by utctime asc

Related

Null field not inserting NULL from empty TEdit

I add new order details to a table in my db.
One of the columns there is named email, in the form I created to add the new order in my delphi application and subsequently the db, I use TEdits to pass the data along.
This is the code:
procedure TForm2.actAddComandaExecute(Sender: TObject);
begin
if dbmodule.comenziConnection.Connected then
begin
if addOrderForm.ShowModal=mrok then
begin
dbmodule.comenziQuery.SQL.Clear;
dbmodule.comenziQuery.SQL.Add( 'insert into `r33758pi_tipotask`.`comenzi` ( stare, client, telefon, email, detalii, livrare, pret, user, status, observatii ) values ( :stare, :client, :telefon, :email, :detalii, :livrare, :pret, :user, :status, :observatii ) ' ) ;
dbmodule.comenziQuery.Params.ParamByName( 'stare' ).AsString := addOrderForm.ComboBoxEx1.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'client' ).AsString := addOrderForm.Edit2.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'telefon' ).AsString := addOrderForm.Edit3.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'email' ).AsString := addOrderForm.Edit4.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'detalii' ).AsString := addOrderForm.Edit5.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'livrare' ).AsString := addOrderForm.ComboBoxEx6.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'pret' ).AsString := addOrderForm.Edit7.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'user' ).AsString := addOrderForm.ComboBoxEx8.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'status' ).AsString := addOrderForm.ComboBoxEx9.Text ;
dbmodule.comenziQuery.Params.ParamByName( 'observatii' ).AsString := addOrderForm.Edit10.Text ;
dbmodule.comenziQuery.ExecSQL ;
end;
end;
end;
If I leave Edit4 empty on the form everything inserts but the field email for that order doesn't have a Null value, it shows just as being empty - not null but no data either.
The column email is set as Null by default in db so that's not the problem.
Screenie from workbench:
There should be 2 NULL showing up between the values there but it's just empty.
Any ideas why?
Using Rad Studio 10 Seattle and dbExpress components
EDIT
comenziQuery is a TSQLQuery
dbmodule is the name of a data module that holds the db components
the dataset is a TSimpleDataSet
the comenziConnection is the name of a TSQLConnection
For any future readers, please do read all the answers comments also, great stuff in there.
An empty string is not the same thing as a NULL string. When it comes to SQL, you need to understand the difference.
You need to add some sort of logic to write string values vs null values, such as...
if addOrderForm.Edit5.Text <> '' then
dbmodule.comenziQuery.Params.ParamByName('detalii').AsString := addOrderForm.Edit5.Text
else
dbmodule.comenziQuery.Params.ParamByName('detalii').Value := NULL;
This way, if the edit control is empty, a NULL will get written to the table field instead of an empty string.
As suggested, this can further be wrapped inside a common function to save you on writing a ton of code:
function NullIfEmpty(const S: string): Variant;
begin
if S <> '' then
Result := S
else
Result := NULL;
end;
And then use it like...
dbmodule.comenziQuery.Params.ParamByName('detalii'):=
NullIfEmpty(addOrderForm.Edit5.Text);
The problem you are having is due to using ParamByName( 'email' ).AsString, which will set the email column to a blank string. If you want it to remain null I would use code like this to clear the parameter,
if Trim(addOrderForm.Edit4.Text) = '' then
dbmodule.comenziQuery.Params.ParamByName('email').Clear
else
dbmodule.comenziQuery.Params.ParamByName('email').AsString := Trim(addOrderForm.Edit4.Text);
You should use TDB* components which handle automatically such problems.

Inserting null and string 'Null in trigger condition

I'm creating a new trigger and want to have both null value and NULL string in :new.SCO_NUMBER validation. I'm getting error when i'm using both (as shown below) but when i use ':new.SCO_NUMBER IS NULL', it works fine. How to use or in this validation.
CREATE OR REPLACE TRIGGER TRIG_SCONUMBER_INSERT AFTER
INSERT ON S_SYN_EAI_SCO_IN FOR EACH row DECLARE XYZ BEGIN XYZ
SELECT XYZ
FROM xyz
WHERE xyz IF inserting
AND :new.SCO_NUMBER IS (NULL
OR 'NULL') THEN varError_Msg := 'SCO Number cannot be NULL in';
varError_id := 1;
varSucceeded := 'N' ;
varErrorExists :=1;
END IF;
In case of T-SQL,
replace new.SCO_NUMBER IS (NULL OR 'NULL') with new.SCO_NUMBER IS NULL OR new.SCO_NUMBER = 'NULL'. This should work for you.
Try this
IF inserting
AND ( :new.SCO_NUMBER IS NULL
OR :new.SCO_NUMBER = 'NULL') THEN
Try this,
(:new.SCO_NUMBER IS NULL OR :new.SCO_NUMBER = 'NULL')

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

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.

How to group the result of a query based on the parameter value

How we can group the result of the query depending up on the parameter passed.
A small stored procedure is shown below. parameter Param is passed to the procedure.
If param value is "f" the result must group by starttime otherwise by using formid. How can i do this. ???I tried the code show below but its not working .
DROP PROCEDURE IF EXISTS Test;
CREATE PROCEDURE Test (Param VARCHAR (2))
BEGIN
SELECT formid, starttime
FROM tbevaluationscoreinfo
CASE Param
when 'F'
then group by starttime;
else
group by formid;
end
END;
One way is to move branching up a level:
IF Param = 'F' THEN
SELECT starttime, count(formid)
FROM tbevaluationscoreinfo
GROUP BY starttime;
ELSE
SELECT formid, count(starttime)
FROM tbevaluationscoreinfo
GROUP BY formid;
END IF;
Another, less recommended solution, is dynamic SQL.
And the third possible solution is:
SELECT
case Param when 'F' then starttime else formid end as group_column,
count(formid),
count(starttime)
FROM
tbevaluationscoreinfo
GROUP BY
group_column;