Alternative to EntityFunctions.AddSeconds for MySQL - mysql

I need to execute an EF LINQ query that adds some seconds to a datetime against MySQL using the standard Oracle supplied dot net connector. Unfortunately it does not support the EntityFunctions.AddSeconds method. Is there an alternative approach?
var result = (from rec in db.Records where EntityFunctions.AddSeconds(rec.SomeDate, rec.SomeSeconds) select rec).FirstOrDefault();

DELIMITER $$
drop function IF EXISTS AddSeconds$$
create function AddSeconds(theDate datetime, seconds int)
RETURNS datetime
DETERMINISTIC
begin
return DATE_ADD(theDate, INTERVAL seconds SECOND);
end$$

Related

MySQL procedure to update a price based on a date change

I am trying to write a procedure that update the the content in one column, based a change in date is more than 20 days. In context, the procedure decreases the price of a good if the time passed since acquired is more than 20 days.
I am using the DATEDIFF function as well as GETDATE() statement but I am really strugling. At this point I am stucked.
Can anybody tell what is wrong with my sql code?
DELIMITER //
CREATE PROCEDURE UPDATE_PRICE
DECLARE #TIMEPASSED AS TIME
SET #TIMEPASSED = GETDATE()
BEGIN
UPDATE sales SET sales.SalesPrice = sales.SalesPrice - 30
WHERE DATEDIFF(#GETDATE(), Sales.AcquisitionDate;
END;;
Any help on this one would be much appreciated
Variable declarations should be in the BEGIN/END block, but they are not really needed in this case. GETDATE() is not a MySQL function. So:
DELIMITER //
CREATE PROCEDURE UPDATE_PRICE
BEGIN
UPDATE sales s
SET s.SalesPrice = s.SalesPrice - 30
WHERE s.AcquisitionDate < CURDATE() - INTERVAL 20 day;
END;
DELIMITER ;
Try this:
DELIMITER //
CREATE PROCEDURE UPDATE_PRICE
DECLARE #TIMEPASSED AS TIME
SET #TIMEPASSED = GETDATE()
BEGIN
UPDATE sales SET sales.SalesPrice = sales.SalesPrice - 30
WHERE DATEDIFF(#GETDATE(), Sales.AcquisitionDate) > 20;
END;

PostgreSQL Date Conversion Function

I have one challenge:
I have the following code in SQL Server and I want to move it to PostgreSQL DBMS.
I adapted it to PostgreSQL just like the following:
CREATE function public.SEMANA_ISO (fecha date) returns integer as $$
DECLARE
semana_ISO int= date_part ('week',fecha)+1
-date_part('week',CAST(date_part('year',fecha) as CHAR(4)) + '0104');
BEGIN
IF (semana_ISO=0)
THEN
semana_ISO=public.SEMANA_ISO(CAST(date_part('year',fecha)-1
AS CHAR(4)) + '12' + CAST(24 + date_part('day',fecha) AS CHAR(2)))+1;
ELSIF ((date_part('month',fecha)=12) AND ((date_part('day',fecha)-date_part('day',fecha))>=28))
THEN
semana_ISO=1;
END IF;
RETURN semana_ISO;
END;
$$ LANGUAGE plpgsql;
As you may see, I tried to make it look the most similar as in SQL Server is.
However when I try to run this function and test it:
Select public.SEMANA_ISO('28/12/2014');
The DMBS shows many errors:
ERROR: operator does not exist: character + unknown
LINE 2: ...rt('week',CAST(date_part('year',fecha) as CHAR(4)) + '0104')
HINT: No operator matches the name and type of the arguments. You may need to add explicit type casts.
QUERY: SELECT date_part ('week', date) +1
-date_part ('week', CAST (date_part ('year', date) as CHAR (4)) + '0104')
CONTEXT: PL / pgSQL function semana_iso (date) at line 5 during initialization of local variables in the statement block
What I try to do is the following.
From the following input date format: dd/mm/yyyy I want to use the function above to show it as the next output format:mm-dd-yyyy
I have thought in doing a simpler function that could receive the date in the format given (dd/mm/yyyy) and using the set datestyle = mdy statement change it in the body of the function and finally print it or return it.
What do you suggest folks?
Your help & time is always appreciated!
A guess you may need a Function like below
CREATE function a_date_conv (fecha date) returns text as $$
select to_char(fecha, 'mm-dd-yyyy');
$$ LANGUAGE sql;
select a_date_conv('08/10/2014')
Result
-------
10-08-2014

Mysql stored function giving different results than original query (some conditions are not working)

I have a weird problem in mysql stored function. The function is returning different result than if I run the query alone. Here is my function:
DELIMITER $$
CREATE DEFINER=`admin`#`%` FUNCTION `getARetention`
(appID int(10), currentDate DATE)
RETURNS int(11)
READS SQL DATA
DETERMINISTIC
BEGIN
RETURN
(SELECT count(DISTINCT UserId)
FROM
Session
WHERE (Date(Started) = currentDate AND AppId=appID));
END
Here is how I call it:
SELECT getARetention(5,DATE('2013-04-03'));
Here is the alone query:
SELECT count(DISTINCT UserId)
FROM
Session
WHERE (Date(Started) = DATE('2013-04-03') AND AppId=5)
The function is returning 2502 which is wrong. Alone query is returning 5, which is correct. Also, if I delete "AND AppId=5" from alone query then it return 2502, which means in the stored function that condition is not working.
Anyone have any idea why? I haven't used mysql for a while, so I am probably missing something.
MySQL cannot distinguish between the variable name and the column name here.
Name the variable otherwise:
DELIMITER $$
CREATE DEFINER=`admin`#`%` FUNCTION `getARetention`
(
_appID int(10),
_currentDate DATE
)
RETURNS int(11)
READS SQL DATA
DETERMINISTIC
BEGIN
RETURN (
SELECT COUNT(DISTINCT UserId)
FROM Session
WHERE appId = _appId
AND started >= _currentDate
AND started < _currentDate + INTERVAL 1 DAY
);
END
$$

Function in postgresql wit ref cursor

Im trying to migrate an oracle procedure to a postgresql function. Here's the function in postgres:
CREATE OR REPLACE FUNCTION tibrptsassure.call_reasons(i_start_date date, i_end_date date, i_intnbr character varying, i_intmodnbr character varying, oc_ref_cursor refcursor)
RETURNS refcursor AS
$BODY$
BEGIN
OPEN oc_ref_cursor FOR
SELECT COUNT(1),INTERACTION_NBR,INTERACTION_ID,INTERACTION_MODULE_NBR,CREATED_BY
FROM tibrptsassure.d_tcare_interaction , tibrptsassure.d_calendar d
WHERE INTERACTION_ID = i_intnbr
AND INTERACTION_MODULE_NBR = i_intmodnbr AND INTERACTION_DATE BETWEEN i_start_date AND i_end_date
AND INTERACTION_DATE BETWEEN d.week_start_date AND d.week_end_date
GROUP BY INTERACTION_NBR;
return oc_ref_cursor;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
But, while executing this function, I dint get any output. Got a message: Query result with 1 row discarded.
begin;
select tibrptsassure.sampleproc_call('10-Feb-2010','31-Dec-2013','30681','Bypass_IDV','funccursor');
FETCH ALL IN "funccursor" ;
COMMIT;
Whats wrong in the query?
This is an issue with pgAdmin and multi-statement transactions. Use psql instead.
Basically pgAdmin doesn't know what to do at that point and so it discards the row and you can't with cursors outside such an environment.

Perl DBI execute not maintaining MySQL stored procedure results

I'm having a problem with executing a stored procedure from Perl (using the DBI Module). If I execute a simple SELECT * FROM table there are no problems.
The SQL code is:
DROP FUNCTION IF EXISTS update_current_stock_price;
DELIMITER |
CREATE FUNCTION update_current_stock_price (symbolIN VARCHAR(20), nameIN VARCHAR(150), currentPriceIN DECIMAL(10,2), currentPriceTimeIN DATETIME)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE outID INT;
SELECT `id` INTO outID FROM `mydb449`.`app_stocks` WHERE `symbol` = symbolIN;
IF outID > 0 THEN
UPDATE `mydb449`.`app_stocks`
SET `currentPrice` = currentPriceIN, `currentPriceTime` = currentPriceTimeIN
WHERE `id` = outID;
ELSE
INSERT INTO `mydb449`.`app_stocks`
(`symbol`, `name`, `currentPrice`, `currentPriceTime`)
VALUES (symbolIN, nameIN, currentPriceIN, currentPriceTimeIN);
SELECT LAST_INSERT_ID() INTO outID;
END IF;
RETURN outID;
END|
DELIMITER ;
The Perl code:
$sql = "select update_current_stock_price('$csv_result[0]', '$csv_result[1]', '$csv_result[2]', '$currentDateTime') as `id`;";
My::Extra::StandardLog("SQL being used: ".$sql);
my $query_handle = $dbh->prepare($sql);
$query_handle->execute();
$query_handle->bind_columns(\$returnID);
$query_handle->fetch();
If I execute select update_current_stock_price('aapl', 'Apple Corp', '264.4', '2010-03-17 00:00:00') asid; using the mysql CLI client it executes the stored function correctly and returns an existing ID, or the new ID.
However, the Perl will only return a new ID, (incrementing by 1 on each run). It also doesn't store the result in the database. It looks like it's executing a DELETE on the new id just after the update_current_stock_price function is run.
Any help? Does Perl do anything funky to procedures I should know about?
Before you ask, I don't have access to binary logging, sorry.
Perhaps you're doing it in a transaction and it's getting rolled back? The row is inserted but never becomes committed and cannot be seen.
I'd try it on your dev server and enable general query log, if in doubt.
Also you may want to know about the INSERT ... ON DUPLICATE KEY UPDATE syntax, which can probably do what you're trying to do anyway.
try
$query_handle->dump_results(15, "\n", '|');
before the bind_columns call to see if it is actually getting the results back, you could also try replace SELECT storedprocedure with SELECT * FROM storedprocedure
You should check that you are running the latest version of DBD::mysql (which is the MySQL-driver used by DBI). There used to be several issues with stored procedures, at least some are fixed in recent versions. Maybe these ressources are also helpful:
http://www.perlmonks.org/?node_id=609098
http://www.perlmonks.org/?node_id=830585