MySQL - str_to_date() not working in update query - mysql

I am trying to perform some calculations and update the table with the calculated value using SQL query. The query used is as follows:
UPDATE `table1` pv inner join
(SELECT Email,IF(`DS Start Date` = "-",Round((DATEDIFF(CURDATE(),STR_TO_DATE(`Start Date`,'%Y-%m-%d')))/365,2),
Round((DATEDIFF(STR_TO_DATE(`DS Start Date`,'%Y-%m-%d'),STR_TO_DATE(`Start Date`,'%Y-%m-%d')))/365,2)) as ba_tenure,
IF(`DS End Date` != "-",Round((DATEDIFF(STR_TO_DATE(`DS End Date`,'%Y-%m-%d'),STR_TO_DATE(`DS Start Date`,'%Y-%m-%d')))/365,2),
Round((DATEDIFF(CURDATE(),STR_TO_DATE(`DS Start Date`,'%Y-%m-%d')))/365,2)) as ds_tenure,
Round((DATEDIFF(CURDATE(),STR_TO_DATE(`Start Date`,'%Y-%m-%d')))/365,2) as overall_tenure
from `table1` where Status = "Active" ) A on (pv.Email = A.Email)
set pv.`Tenure (Yrs)` = A.overall_tenure,pv.`BA Team Tenure` = A.ba_tenure,pv.`DS Team Tenure` = A.ds_tenure
When I execute the select statement, the query runs good. But when I execute the update query it throws the error
#1411 - Incorrect datetime value: '-' for function str_to_date
I cannot figure out the issue. Can anyone help me to solve this issue?

If your second if you have DS Start Date for true and false but for false this mean that DS Start Date is equal to '-' and this value is not valid for str_to_date
IF(`DS End Date` != "-",
Round((DATEDIFF(STR_TO_DATE(`DS End Date`,'%Y-%m-%d'),STR_TO_DATE(`DS Start Date`,'%Y-%m-%d')))/365,2),
Round((DATEDIFF(CURDATE(),STR_TO_DATE(`DS Start Date`,'%Y-%m-%d')))/365,2)) as ds_tenure,

Related

Update query in SQL: command not ended properly

update fare_strategy set sales_date_to = ’07-SEP-22’
where dep_date_to is not null
and market_id in
(select market_id
from fare_strategy_markets
where set_type = ‘STANDARD’
);
In the following query, I'm getting error as SQL command not properly ended.
try to change like this because in your query you used ’ this is not valid so i just change it to ' so it's works fine
update fare_strategy set sales_date_to = '07-SEP-22' where dep_date_to is
not null and market_id in (select market_id from
fare_strategy_markets where set_type = 'STANDARD');

mysql date range query, when the field is not sent anything for the 'between' statement

I have this query, which returns me 7 records
Now if I add this line 'AND date_format (ds.date_emission,'% Y-% m-% d ') BETWEEN' 'AND' '', nothing returns me, I want that when the date range is empty I need that I also returned the 7 records
Please refer answer below.
I have added two variable replace inStartDate variable with a range start date and inEndDate with range end date.
SELECT ds.id
FROM documentos_salida ds
WHERE ds.terceros_id = 329
AND ds.estado =0
AND ds.tipo_documento ='Factura'
AND ds.saldo_pendiente_factura >0
AND (ds.fecha_vencimiento > now() or
ds.fetcha_vencimiento = NOW())
AND ds.numero_documento LIKE '%%'
AND ( CASE WHEN (inStartDate = '' AND inEndDate = '')
THEN TRUE
ELSE (date_format(ds.fetcha_emision, '%Y-%m-%d') BETWEEN inStartDate AND inStartDate)
END)
ORDER BY ds.fecha_emision DESC;

query execution failed for dataset 'Dataset1'. Incorrect syntax near ','

Every time I try to generate a report from SSRS, I always get this error:
This is my query in DataSet1
SELECT [DATE]
,[SOURCE]
,[DESTINATION]
,[REFERENCE#]
,[ITEMCODE]
,[DESCRIPTION]
,[UM]
,[PRICE]
,[QTY]
,[AMOUNT]
,[MFG]
,[EXP]
,[LOT]
,[TRANS]
,[CONSIGNOR]
,[DRDATE]
,[ID]
FROM
[AcctgCon].[dbo].[DelTrans]
WHERE
Date BETWEEN #start_date AND #end_date
AND Source = #source
AND Destination = #destination
AND Trans = #transaction
AND Consignor = #consignor
I'm trying to figure out where the error might be, but still can't make it work
You should change the '=' sign in the where condition to 'IN' for the parameters you are allowing multiple values for.

Calling stored procedure in MySQL takes forever to execute

I have a stored procedure which I'm trying to call, and it takes forever to execute. I have no idea what's wrong. A similar stored procedure in another database executes perfectly. I'm not well-versed with MySQL Workbench, so I don't know if the database settings are different or something.
Following is my stored procedure:
CREATE
DEFINER = `admin`#`%`
PROCEDURE `calculate_daily_coil_moved_by_crane_data`()
BEGIN
set #curr_date = curdate();
set #pre_date = date_add(curdate(), interval -1 day);
set #a_shift_start_ts = concat(#pre_date, ' 06:00:00');
set #a_shift_end_ts = concat(#pre_date, ' 13:59:59');
set #b_shift_start_ts = concat(#pre_date, ' 14:00:00');
set #b_shift_end_ts = concat(#pre_date, ' 21:59:59');
set #c_shift_start_ts = concat(#pre_date, ' 22:00:00');
set #c_shift_end_ts = concat(#curr_date, ' 05:59:59');
SELECT #curr_date,
#pre_date,
#a_shift_start_ts,
#a_shift_end_ts,
#b_shift_start_ts,
#b_shift_end_ts,
#c_shift_start_ts,
#c_shift_end_ts;
#SET DATA
insert into daily_coil_move_by_crane_data_for_report (crane_id, crane_name, date, a_shift, b_shift, c_shift)
select cr.id, cr.name, #pre_date, 0, 0, 0
from yms_phase3.crane cr
where active = 1
order by cr.name;
#----------------------------------------------------------------------------------------------------
#--> COILS MOVED BY CRANE A Shift <--
#----------------------------------------------------------------------------------------------------
SET #shift = 'A';
#FETCH ROW DATA
update daily_coil_move_by_crane_data_for_report
set a_shift = ifnull((select COUNT(*)
FROM yms_phase3.workorder_history in_data
where in_data.crane_id = daily_coil_move_by_crane_data_for_report.crane_id
and current_execution_status IN (6 , 7)
and in_data.pick_ts between #a_shift_start_ts and #a_shift_end_ts
group by in_data.crane_name), 0)
where (a_shift is null or a_shift = 0);
#----------------------------------------------------------------------------------------------------
#--> COILS MOVED BY CRANE B Shift <--
#----------------------------------------------------------------------------------------------------
SET #shift = 'B';
#FETCH ROW DATA
update daily_coil_move_by_crane_data_for_report
set b_shift = ifnull((select COUNT(*)
FROM yms_phase3.workorder_history in_data
where in_data.crane_id = daily_coil_move_by_crane_data_for_report.crane_id
and current_execution_status IN (6 , 7)
and in_data.pick_ts between #b_shift_start_ts and #b_shift_end_ts
group by in_data.crane_name), 0)
where (b_shift is null or b_shift = 0);
#----------------------------------------------------------------------------------------------------
#--> COILS MOVED BY CRANE C Shift <--
#----------------------------------------------------------------------------------------------------
SET #shift = 'C';
#FETCH ROW DATA
update daily_coil_move_by_crane_data_for_report
set c_shift = ifnull((select COUNT(*)
FROM yms_phase3.workorder_history in_data
where in_data.crane_id = daily_coil_move_by_crane_data_for_report.crane_id
and current_execution_status IN (6 , 7)
and in_data.pick_ts between #c_shift_start_ts and #c_shift_end_ts
group by in_data.crane_name), 0)
where (c_shift is null or c_shift = 0);
#----------------------------------------------------------------------------------------------------
#INSERT ALL CRANE ENTRY
insert into daily_coil_move_by_crane_data_for_report (crane_id, crane_name, date, a_shift, b_shift, c_shift)
select -1, 'ALL', #pre_date, SUM(a_shift), sum(b_shift), sum(c_shift)
from daily_coil_move_by_crane_data_for_report
where date = #pre_date
group by date;
#UPDATE TOTAL
update daily_coil_move_by_crane_data_for_report
set total_coils_moved = (a_shift + b_shift + c_shift)
where date = #pre_date;
END
Also tried to execute the query from Java using the following:
jdbcTemplate.execute("CALL calculate_daily_coil_moved_by_crane_data;");
But it gives me the following Exception:
java.sql.SQLException: Lock wait timeout exceeded
Any workaround I can do to solve this?
Please try and edit the configuration file, also search for the same here on stack. There are certain possibilities while checking this out,
Check and edit the config file on Hard drive for MySQL increase the cache capacity and default values as the default values are in KB's the memory allocated is very less and to execute such a big procedure it should at least be some MB.
Increase the connection String timeout, that is by setting up right time in seconds. by default it is 60 seconds, which is very less for executing such a procedure, I think in c# at least we set it to '0' seconds which means that it shall not get timed-out till the query is executed.
If Any left Joins/ inner query please try and check whether the same output is produced in inner joins ? as inner joins are faster than left or right joins.
Add Indexes, have foreign key references properly mapped for faster execution of query.
Hope it works.

Assigning a value from another database and function - MySQL variable scope

I am using MySQL to make a report showing the number of hours billed for a particular date range and project. The complexity is that the date range is variable for each project (different start month and start day). This information is coming from a value in another database/table.
I have the following UDF in MySQL:
DELIMITER //
CREATE FUNCTION TimeLeft(startday INT, today INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE s INT;
IF startday < today THEN SET s = 0;
ELSE SET s = 1;
END IF;
RETURN s;
END //
DELIMITER;
I use that function in the following query, which is supposed to take the value returned in the TimeLeft function to determine the values for the start month (month(curdate())-#xx) and start day (#yy) for each project to calculate the hours:
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
Here's how I am setting the values for #xx and #yy:
SET #xx = 0; #this is the value that we will use to manipulate the month for the date range
SET #yy = 0;
#yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT #xx:= TimeLeft(#yy,dayofmonth(curdate()));
I am getting some issues:
#yy is not getting the value - possibly my syntax is wrong?
The variables are set at the top of the code, so they are not getting changed for each project as they should be (there should be a different #xx and #yy for each project since each one has a different start and end date).
Here's the full query:
#below is where I assign the variables
SET #xx = 0; #this is the value that we will use to manipulate the month for the date range
SET #yy = 0;
#yy:= SELECT start_day_of_month FROM dashboard.client; #this doesn't seem to work
SELECT #xx:= TimeLeft(#yy,dayofmonth(curdate()));
# below is the MySQL query that is meant to use the variables assigned above
SELECT X.expr1 AS 'Project Name', #monthly_hours - SUM(X.expr2) AS 'Hours Billed
FROM
(SELECT
projects.name AS expr1
, sum(time_records.value) AS expr2
FROM project_objects
INNER JOIN projects
ON projects.id = project_objects.project_id
INNER JOIN time_records
ON time_records.parent_id = project_objects.id
WHERE time_records.parent_type = 'Task'
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
AND time_records.record_date <= curdate()
GROUP BY projects.name
UNION
SELECT
projects.name AS expr1
, sum(time_records.value) as expr2
FROM projects
INNER JOIN time_records
ON projects.id = time_records.parent_id
WHERE time_records.parent_type = 'Project'
AND time_records.record_date >= concat('2012/', month(curdate())-#xx , '/' , #yy)
AND time_records.record_date <= curdate()
GROUP BY projects.name) X
GROUP BY X.expr1
I think there is some issue of where I am assigning the variables #xx and #yy. These should be done for each individual Project, so putting them up on the top is probably not the best idea. I'm also not sure if I am assigning the #yy value correctly. It's supposed to query the value of the field of a table that is in another database but it keeps throwing a syntax error on the #yy assignment to that field.
Assign value to #yy inside select:
SELECT #yy:= start_day_of_month FROM dashboard.client;