How to call a stored procedure and alter the database table in 1 go - mysql

I'm really struggeling with this for some time now.
I have a MySQL database and a lot of data. It is a formula1 website i have to create for college.
Right now the j_tracks_rounds_results table is filled with data but one column is not filled out. It's the rank column.
I created a stored procedure as the following:
DROP PROCEDURE `sp_rank`//
delimiter ##
PROCEDURE `sp_rank`(sid INT)
begin
set #i = 0;
SELECT `performance`, subround_id, #i:=#i+1 as rank
FROM `j_tracks_rounds_results`
where subround_id = sid
order by `subround_id`,`performance`;
end
delimiter ;
The output is like the following:
rec.ID PERFORMANCE SUBROUND_ID RANK
87766 100,349114516829 1 1
93040 101,075635087628 1 2
88851 101,664302543497 1 3
It gets the results and ads a rank to it, sorted on performance so the lowest performance gets rank1 etc...
What i am trying to achieve is to put the rank back into the table. Like an ALTER command for the column "rank".
How would i be able to accomplish this?

Basically don't...
Create table to hold the key (rec.id ?) and the rank. Truncate it to get rid of the previous results then use insert into ... with your query and then join to it.
You really don't want to be altering tables in your normal running, guaranteed some one will use the column when it isn't there, and then when you look at the fault it will be...
People just don't look for table structures changing through the application lifetime, it's a screw up waiting to happen.

You are misapplying your SQL statements. You want the UPDATE command, not ALTER.
eg.
UPDATE table SET rank=#i WHERE subround_id=#id

Related

In MySQL, how do you change the value of a column in a table depending on an updated column in another table?

I'm attempting to create a trigger that increases the value of a column INCOME in the Salary database by 500 each time the value of WorkYear in the Employee table is increased by one year. For example, if the workYear is 4 and the salary is 1000, the salary should be 1500 if the workYear is increased by one year, 2000 if the workYear is increased by two years, and so on.
I tried to create such trigger and here is my code :
DELIMITER $$
create trigger increment AFTER UPDATE on employee
for each row
BEGIN
IF OLD.workYear <> new.workYear THEN
update salary
set income = (income + (new.workYear-old.workYear)*500);
END IF;
END$$
The idea behind this code is that after we update the workYear, the trigger should increase the salary by the difference of years * 500, (new.workYear-old.workYear)*500, but it increases all the rows by the same number, (5500 if we add one year, 27500 if we add two years, etc.) which not what we are looking for .
I am new to MySQL and would appreciate it if someone could assist me with this.
Thanks in advance
FaissalHamdi
In MySQL an AFTER trigger can affect the entire table, so you must declare the update scope in the form of criteria or a join.
Create Trigger in MySQL
To distinguish between the value of the columns BEFORE and AFTER the DML has fired, you use the NEW and OLD modifiers.
The concept is similar but each RDBMS has a slightly different syntax for this, be careful to search for help specifically on your RDBMS.
In the original query these special table references were used to evaluate the change condition however the scope of the update was not defined.
Assuming that there is a primary key field called Id on this salary table.
Also note that if you can, the query should be expressed in the form of a set-based operation, instead of static procedural script, this will be more conformant to other database engines.
So lets try this:
DELIMITER $$
create trigger increment AFTER UPDATE on employee
for each row
BEGIN
UPDATE salary s
SET income = (income + (new.workYear-old.workYear)*500)
WHERE s.Id = OLD.Id
END$$

how to set limit on table containing record

I am using mySQL
Is there any way to set limit of table record/row? I have table X and want to set limit of total records/rows on table, for example 2rows. So no one can insert third record in table. This table should not allow to insert third record.
I do not want to use Triggers.
You can do it this the user grants, so the user cant write into this table and you can create a separate User for administration this table.
seee Manual : https://mariadb.com/kb/en/mariadb/grant/
If you dont want to use triggers, you 'll have to check the number of rows inside your application (if any).
Create an AFTER INSERT trigger on the table. - it's the only way to do it.
create trigger TableLimit
on TableName
after insert
as
declare #countTableRows int
select #countTableRows = Count(*)
from TableName
if #countTableRows > 2
begin
rollback
end
go

MySQL views with arguments

I have been working on a pretty large database this last week. Basically I am taking an Access database and converting it to a MySQL database. I have seccessfully converted all the tables and views to MySQL. However I have a view that requires input from the user, the date. The other view is the view that will be call.
view 1 - compiled_fourweeks - needs date
view 2 - metrics_fourweeks - uses `compiled_fourweeks in query.
I was thinking of a precedure but I won't be able to reference the columns in the query.
I am kind of running out of ideas at this point.
If I understand correctly, you need to execute a view (metrics_fourweeks) that needs data from another view (compiled_fourweeks), and this last view requires input from the user.
I would go with the procedure approach:
create procedure fourWeeksData(d date)
create or replace view compiled_fourweeks
select ...
from ...
where recordDate = f -- Just an example; use whichever where clause you need
...;
select * from metrics_fourweeks;
end
If your database will be used just by a single user, your problem is solved. But if your database is meant to be used by more than one user... well, you can use temporary tables:
create procedure fourWeeksData2(d date)
drop table if exists temp_compiled_fourweeks;
create temporary table temp_compiled_fourweeks
select ...
from ...
where recordDate = f -- Just an example; use whichever where clause you need
...;
-- You will need to create the required indexes for this new temp table
-- Now replicate the SQL statement, using your new temp table
select ...
from temp_compiled_fourweeks
...;
end
Hope this helps you.

Multiple MySQL queries (no PHP)

I am wondering if it is possible to perform a SQL query then update another table with the generated ID and continue through all of the rows?
I have this SQL query that works but what I need to do is after each row is added to cards to then update merged.cars_id with the last generated ID so they are linked. normally I would do this with PHP but ideally I would like to just do it with MySQL if possible.
MAIN QUERY
INSERT INTO cards (first_contact_date, card_type, property_id, user_id)
SELECT first_contact_date, 'P', property_id, user_id FROM merged
THEN I NEED WITH MATCHING ROWS (Roughly)
UPDATE merged SET merged.card_id = LAST_INSERT_ID (FROM ABOVE) into the matching record..
Is something like this possible and how do I do it?
I would recommend using MySQL triggers to do this
http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html
A trigger is a function that will be executed AFTER or BEFORE the INSERT or DELETE or UPDATE is done over any record of your table.
In your case you need to do a AFTER INSERT on cards that just updates the merged table. Make sure its AFTER insert as you wont be able to access the new row's ID otherwise.
The code would look something like this, assuming the id field from the cards table its named "id"
delimiter |
CREATE TRIGGER updating_merged AFTER INSERT ON cards
FOR EACH ROW BEGIN
UPDATE merged SET card_id = NEW.id;
END;
|
delimiter ;
May I suggest Stored Procedures?
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
--EDIT--
Ah yes, triggers. For this particular situation, Jimmy has the answer. I will leave this post for the sake of the link.
I would set up a trigger to do this. For mysql, read http://dev.mysql.com/doc/refman/5.0/en/triggers.html. This is what triggers are designed to handle.

Call a Stored Procedure From a Stored Procedure and/or using COUNT

Ok, First off, I am not a mysql guru. Second, I did search, but saw nothing relevant related to mysql, and since my DB knowledge is limited, guessing syntactical differences between two different Database types just isn't in the cards.
I am trying to determine if a particular value already exists in a table before inserting a row. I've decided to go about this using two Stored procedures. The first:
CREATE PROCEDURE `nExists` ( n VARCHAR(255) ) BEGIN
SELECT COUNT(*) FROM (SELECT * FROM Users WHERE username=n) as T;
END
And The Second:
CREATE PROCEDURE `createUser` ( n VARCHAR(255) ) BEGIN
IF (nExists(n) = 0) THEN
INSERT INTO Users...
END IF;
END
So, as you can see, I'm attempting to call nExists from createUser. I get the error that no Function exists with the name nExists...because it's a stored procedure. I'm not clear on what the difference is, or why such a difference would be necessary, but I'm a Java dev, so maybe I'm missing some grand DB-related concept here.
Could you guys help me out by any chance?
Thanks
I'm not sure how it helped you, but...
why SELECT COUNT(*) FROM (SELECT * FROM Users WHERE username=n) and not just SELECT COUNT(*) FROM Users WHERE username=n?
Just make the user name (or whatever the primary application index is) a UNIQUE index and then there is no need to test: Just try to insert a new record. If it already exists, handle the error. If it succeeds, all is well.
It can (and should) all be one stored procedure.