the value doesn't show on the sp - mysql

I tried a simple app for testing but doesn't get the value on my table.
what I am doing wrong?
I want just put a value in a variable (not default) and then from the variable put it on the table.
like so
CREATE DEFINER=`mysql`#`localhost`
PROCEDURE `calcularferiado`(
in StartDate date,
in EndDate date,
in Duration int)
BEGIN
DECLARE DateDiff1 Int;
SELECT DateDiff1 = DATEDIFF(StartDate,EndDate);
INSERT INTO my_schema.feriados(inicio,fin,activo)
values (StartDate, EndDate, DateDiff1);
END

SEt DateDiff1 = DATEDIFF(StartDate,EndDate);
not
SElect DateDiff1 = DATEDIFF(StartDate,EndDate);

Related

MySQL Stored Procedures - Adding integer variable to date returns null

I am writing my first mysql procedure. I have a date variable and 2 integer variables. I am multiplying the two integer variables and adding the resultant integer to the date variable.
For example:
pint=6;
noftimes=3
sdate=2020-05-05
totDays=pint*noftimes
edate=2020-05-05+totDays
I am able to multiple pint*noftimes but not add sdate+totDays. Whereas If I add sdate+10 then I am getting a correct incremental date value. The following is my procedure:
DELIMITER $$
CREATE DEFINER=`pattu`#`localhost` PROCEDURE `getFieldWorkDates`(IN `p_id` INT, OUT `totDays` INT, OUT `edate` DATE)
BEGIN
DECLARE noftimes int;
DECLARE pint int;
DECLARE sdate DATE;
DECLARE tdays int;
SELECT startDate into sdate from projects where idprojects=p_id;
SELECT projectDuration into noftimes from projects where idprojects=p_id;
SELECT recFreq into pint from projects where idprojects=p_id;
SET totDays=pint*noftimes;
SET edate = sdate+(pint*noftimes);
END$$
DELIMITER ;
When I execute this, I am getting the message, your query has been executed successfully. 0 rows affected
SET edate = sdate+(pint*noftimes);
You cannot add integer to date. Use DATE_ADD() function.
CREATE
DEFINER=pattu#localhost
PROCEDURE getFieldWorkDates ( IN p_id INT,
OUT totDays INT,
OUT edate DATE)
SELECT recFreq * projectDuration,
startDate + INTERVAL recFreq * projectDuration DAY
INTO totDays,
edate
FROM projects
WHERE idprojects=p_id;

Convert postgresql trigger to mysql trigger

I'm trying to transpose a postgres trigger to a mysql trigger. It automatically adds fields to the row according to the date added
CREATE FUNCTION convert_date ()
RETURNS trigger
AS $$
declare
date_min DATE;
date_max DATE;
temp_year INTEGER;
begin
SELECT SUBSTRING(NEW."dc_date_label",0,5)::integer
INTO temp_year;
SELECT date(temp_year || '-01-10')
INTO date_min;
SELECT date(temp_year +1 || '-09-30')
INTO date_max;
NEW."dc_date_start" = date_min;
NEW."dc_date_end" = date_max;
RETURN new;
end;
CREATE TRIGGER trig_b_i_compute_date()
BEFORE INSERT
ON campaigns
FOR EACH ROW
EXECUTE PROCEDURE convert_date();
This is what i've done on mysql :
DELIMITER //
CREATE TRIGGER trig_b_i_compute_date
BEFORE INSERT ON campaigns
FOR EACH ROW
BEGIN
DECLARE date_min DATE;
DECLARE date_max DATE;
DECLARE temp_year INTEGER;
SET temp_year = SELECT CONVERT( SUBSTRING(NEW.dc_date_label,1,5), UNSIGNED INTEGER) ;
SET date_min = SELECT CONVERT( CONCAT(temp_year,'-01-10'), DATE);
SET date_max = SELECT CONVERT( CONCAT(temp_year + 1, '09-30'), DATE);
SET NEW.dc_date_start = date_min;
SET NEW.dc_date_end = date_max;
END;
//
DELIMITER ;
However I get an error :
MySQL server version for the right syntax to use near 'SELECT CONVERT( SUBSTRING(NEW.dc_date_label,1,5), UNSIGNED INTEGER) ;
What is wrong with the procedure ?
If you use SELECT in a SET statement, you need to put it in parentheses:
SET temp_year = (SELECT ...);
But in your case you don't need a SELECT and you can just skip it:
SET temp_year = CONVERT(...);
You can also use the SELECT INTO syntax in MySQL:
SELECT CONVERT(...) INTO temp_year;
And there is no need to declare date_min and date_max. Also no need to cast everything explicitly. Your trigger body could be:
DECLARE temp_year INTEGER;
SET temp_year = CONVERT( SUBSTRING(NEW.dc_date_label,1,5), UNSIGNED);
SET NEW.dc_date_start = CONCAT(temp_year, '-01-10');
SET NEW.dc_date_end = CONCAT(temp_year + 1, '-09-30');
I don't know how dc_date_label looks like, and why the year should be 5 characters long. So I kept the year extraction as it is. But if it's a DATE, DATETIME or TIMESTAMP, you can just use the YEAR function:
SET temp_year = YEAR(NEW.dc_date_label);
And since it's much shorter, you could also use it inline and skip the temp_year variable:
SET NEW.dc_date_start = CONCAT(YEAR(NEW.dc_date_label), '-01-10');
SET NEW.dc_date_end = CONCAT(YEAR(NEW.dc_date_label) + 1, '-09-30');
And last one: Remove the semicolon after END. It might work, but it doesn't belong there.

How can I get Month Difference from two dates which are stored in Table in the format YYYYMM

My table has a column date_period which stores Date in the format YYYYMM. I want to write a query which inserts date in date_period column in the format YYYYMM if there is no entry till current month.
For Example: the date period has entry till October 2015 so it will contain the value 201510. Now I want to check and insert data till current month if it is not present. So the entries will be now 201511, 201512, 201601
How can I achieve this?
try this way, may it will help you
DECLARE #v DATE= getdate()
declare #Currentdate varchar(10)
set #Currentdate=CONVERT(VARCHAR(10), #v, 112)
/*#Currentdate string is in format '20160129'*/
IF NOT EXISTS(select * from Table1 where date_period=LEFT(#Currentdate,6))
begin
insert into Table1(date_period)values(LEFT(#Currentdate,6))
end
Try this
i think this will be the complete solution for your problem
declare #monthcount int
DECLARE #v DATE= getdate()
declare #lastsavedMonth varchar(20)= (select MAX(date_period) from Table1)
declare #Lastsaveddate varchar(20)= #lastsavedMonth+''+RIGHT(CONVERT(VARCHAR, 100 + DATEPART(d,#v)), 2)
set #monthcount=datediff(month,#Lastsaveddate,CONVERT(VARCHAR(10), #v, 112))
while #monthcount>=0
begin
declare #dateofsavingmonth varchar(20)
if(#monthcount=0)
begin
set #dateofsavingmonth=CONVERT(VARCHAR(10),#v,112)
end
else
begin
set #dateofsavingmonth=CONVERT(VARCHAR(10), dateadd(month,-#monthcount,#v),112)
end
IF NOT EXISTS(select * from Table1 where date_period=LEFT(#dateofsavingmonth,6))
begin
insert into Table1(date_period)values(LEFT(#dateofsavingmonth,6))
end
set #monthcount =#monthcount-1
end

How to reduce time to process data in procedure of mysql

Thank you forum...please help me..
I have table which contain TagName and other table contains taglog .im passing tag names to procedure called GetAvg which will return avg of all tags.it works well, but it takes about 35 sec to show 100 tag values.how to reduce time .please help me im new in database.
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetAvg`(IN FromTime datetime, IN ToTime datetime)
BEGIN
DECLARE no_more_alarms INT DEFAULT 0;
DECLARE TempTagName VARCHAR(45);
DECLARE val FLOAT;
DECLARE cur_tag CURSOR FOR
select Tag_AVG from Report
where(Tag_AVG IS NOT NULL );
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET no_more_alarms = 1;
DROP TABLE IF EXISTS `tempAVG`;
CREATE TABLE tempAVG (
val FLOAT
);
OPEN cur_tag;
FETCH cur_tag INTO TempTagName;
REPEAT
SELECT AVG(value) INTO val
FROM jas_taglog
WHERE ((TagId = (select TagId from jas_tags where jas_tags.Name = TempTagName)) AND jas_taglog.LogTime between FromTime and ToTime) ;
INSERT INTO tempAvg(Val)
VALUES (val);
FETCH cur_tag INTO TempTagName;
UNTIL no_more_alarms = 1
END REPEAT;
CLOSE cur_tag;
SELECT * FROM tempAVG;
END
You are manually implementing loops that could be written in a single query:
...
BEGIN
INSERT INTO tempAvg
SELECT AVG(jas_taglog.value)
FROM jas_taglog
JOIN jas_tags USING (TagId)
JOIN Report ON jas_tags.Name = Tag_AVG
WHERE jas_taglog.LogTime BETWEEN FromTime AND ToTime
GROUP BY Tag_AVG;
END

Select in MySQL stored procedure not returning values

I have a stored procedure, shown below, which I created to add dollar sales to a table (WeeklySales) which currently stores only unit sales. The cursor operates on on the WeeklySales table. The pricing data is stored in the Pricing table. The Pricing table actually contains changes in prices. The effective date for a price change is stored in Pricing.effectiveDate, so I have to find the pricing which was effective for the week in which the unit was sold (which is stored in WeeklySales.weekStart).
The problem I'm having is that the first select after the IF doesn't return anything. I've confirmed that this select does return a value when I run it outside of the procedure using the values which it would be called with inside the procedure. I'm not sure what's wrong here, but I'm guessing maybe this has to do with the fact that the this select is operating on a table which is different from the cursor? Anyone know? Is there a better way to do this?
DELIMITER //
CREATE PROCEDURE `createWeeklyPricing` (IN startDate DATE, IN endDate DATE)
BEGIN
--
-- Populate the proceeds column using the Pricing table
DECLARE product VARCHAR(255);
DECLARE weekStart DATE;
DECLARE units, done INT;
DECLARE proceeds DECIMAL(6,2);
DECLARE effectiveDate DATE;
DECLARE currentRow CURSOR FOR SELECT `weekStart`, `product`, `units` FROM `WeeklySales` WHERE `weekStart` >= startDate AND `weekStart` <= endDate;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN currentRow;
SET done = 0;
WHILE done = 0 DO
FETCH currentRow INTO weekStart, product, units;
IF done = 0 THEN
SELECT MAX(`effectiveDate`) FROM `Pricing` WHERE `effectiveDate` <= weekStart AND `product` = product INTO effectiveDate;
SELECT `proceeds` FROM `Pricing` WHERE `effectiveDate` = effectiveDate AND `product` = product INTO proceeds;
UPDATE `WeeklySales` SET `proceeds` = units * proceeds WHERE `weekStart` = weekStart AND `product` = product;
END IF;
END WHILE;
CLOSE currentRow;
END//
echo (select) weekstart before the if statement...
If it returns null change the select FROM WeeklySales WHERE weekStart between startDate AND endDate
you need to use the INTO before FROM and variable needs '#' sign
change it to
SELECT MAX(`effectiveDate`) INTO #effectiveDate FROM `Pricing` WHERE `effectiveDate` <= weekStart AND `product` = product ;
hope this helps
This is because your variable name is overwriting your column name:
You have a variable named 'effectiveDate'
You have a column named 'effectiveDate'
SELECT MAX(`effectiveDate`) ...
Is MAX-ing the variable effectiveDate, not the column
Try naming the variable maxEffectiveDate
Beware that variables are case insensitive. This happened to me when i tried to select column IsBackUp into variable isBackUp (notice the i).