Mysql- Not allowing duplicate entries to be inserted - mysql

I have the following Stored procedure with me which allows to insert into the Database.I want to change the the stored procedure such that duplicate entries should not be entered.The columns that I want to use for checking the duplicate are Material_Name and Material_Data.how should i change the SP? Someone help me.
CREATE PROCEDURE `sp_upload_file`(IN Training_Id INT,IN filename VARCHAR(200), IN path VARCHAR(200),IN materialdata MEDIUMBLOB)
BEGIN
INSERT INTO `training_material`
(`Training_Id`,
`Material_Name`,
`Material_Path`,
`Material_Data`,
`Created_Date`,
`Modified_Date`)
VALUES
(Training_Id,
filename,
path,
materialdata,
NOW()
,NOW());
END$$
DELIMITER ;

alter the table by creating UNIQUE constraint,
ALTER TABLE training_material
ADD CONSTRAINT trainmat_UQ UNIQUE(Material_Name, Material_Data)

Related

Store procedure and foreign key checks

I am trying to create a store procedure to insert data into my joining table which contains two foreign keys (one for members and one for centres)
With straight SQL (via phpmyadmin) i can change values in the table, however with a store procedure I just get error: 1452.
How can I write to the table without causing the error and without disabling the foreign key constraints completely. I understand there's nothing to prevent people from entering the wrong values, the idea is that the user interface will prevent that ultimately. However, if there's a better way within the database I’d love to hear it.
The sql that works is:
INSERT INTO `tblmembers_has_tblcentres` (`tblMembers_MemberID`,
`tblCentres_CentreID`, `DateMemberJoinedCentre`) VALUES ('92', '2',
CURRENT_TIMESTAMP);
And my store procedure looks like this:
CREATE DEFINER=`root`#`localhost` PROCEDURE `Add_Memb_to_Centre`(IN `iMember`
INT, IN `iCentre` INT)
SQL SECURITY INVOKER
INSERT INTO `tblmembers_has_tblcentres` (`tblMembers_MemberID`,
`tblCentres_CentreID`, `DateMemberJoinedCentre`) VALUES ('iMember', 'iCentre',
CURRENT_TIMESTAMP)
You are trying to insert the string values "iMember" and "iCentre" rather than their variable contents. Keep using the backticks:
CREATE DEFINER=`root`#`localhost` PROCEDURE `Add_Memb_to_Centre`(IN `iMember`
INT, IN `iCentre` INT)
SQL SECURITY INVOKER
INSERT INTO
`tblmembers_has_tblcentres`
(
`tblMembers_MemberID`,
`tblCentres_CentreID`,
`DateMemberJoinedCentre`
)
VALUES ('iMember', 'iCentre', CURRENT_TIMESTAMP) -- WRONG
VALUES (`iMember`, `iCentre`, CURRENT_TIMESTAMP) -- CORRECT

Attempting to insert into a table then update a field within the same stored procedure

I'm attempting to create a procedure that is a basic insert into a table, and then performs a quick update on another table afterwards in MySQL. Please find the code below:
DROP PROCEDURE IF EXISTS `sp_insertUserSocial`
GO
CREATE PROCEDURE sp_insertUserSocial
(
IN p_userSocialID INT(11),
IN p_socialID INT(11),
IN p_userID INT(11),
IN p_referralID INT(11)
)
BEGIN
INSERT INTO UserSocial
(
userSocialID,
socialID,
userID,
referralID
)
VALUES
(
IN p_userSocialID,
IN p_socialID,
IN p_userID,
IN p_referralID
) ;
UPDATE Users
SET connCount = connCount + 1
WHERE UserID = p_referralID;
END
GO
In PHPAdmin it's giving me a syntax error, but I'm not sure where exactly it is? It says line 23, which makes me think it's the semi-colon but I thought that these were needed after an insert statement?
Any help is appreciated, thanks!
I see a couple of problems:
GO, must specify the DELIMITER. 19.1. Defining Stored Programs.
In the INSERT (13.2.5. INSERT Syntax), the IN is optional to pass parameters to the stored procedure (13.1.15. CREATE PROCEDURE and CREATE FUNCTION Syntax), but not part of the syntax of the INSERT.
SQL Fiddle demo

create trigger on update to insert old values into other table in MYSQL

I have two tables. The first is my person table which has id, name, creation_date as values, I have a old_person table (id, name, modified_date) which I want to populate the value of person before it actually changes. How would I go about that? I have tried triggers but failed.
I tried as follows
create trigger Person_Trigger Update on person
before update
as
insert into old_person(id, name, modified)
select id, new.name, getdate()
from person
It's giving me syntax errors...Not many Trigger references out there either, a little push would be greatly appreciated!
Have a look at the following example
SQL Fiddle DEMO
IO hade a bit of trouble myself, but from How to Create Triggers in MySQL there was a line that made me think
The first MySQL command we’ll issue is a little unusual:
DELIMITER $$
Our trigger body requires a number of SQL commands separated by a
semi-colon (;). To create the full trigger code we must change
delimiter to something else — such as $$.
Finally, we set the delimiter back to a semi-colon:
DELIMITER ;
So in the SQL Fiddle I changed the query terminator to GO and that seemed top work.
CREATE TABLE person
(
id INT,
name varchar(20)
)
GO
CREATE TABLE old_person
(
id INT,
name varchar(20),
modified DATETIME
)
GO
CREATE TRIGGER Person_Trigger before update on person
FOR EACH ROW BEGIN
INSERT INTO old_person(id, name, modified)
VALUES (OLD.id, OLD.name, NOW());
END
GO
INSERT INTO person VALUES (1,'TADA')
GO
UPDATE person SET name = 'FOO'
GO
Try this:
DELIMITER \\
CREATE TRIGGER `Person_Trigger`
BEFORE UPDATE ON `Person`
FOR EACH ROW
BEGIN
DECLARE date_modified datetime;
SET date_modified = NOW();
INSERT INTO old_person(id, name, modified)
VALUES (OLD.id, OLD.name, date_modified);
END\\
This syntax works for me on my own projects. You may also need to declare delimiters before you begin the trigger. Also if you want to use the NEW keyword it should be AFTER update. Switch to the OLD keyword if you are going to keep using BEFORE update on your trigger.

MySQL Trigger Creation. What's wrong with my trigger?

I'm trying to create a trigger, however I keep getting back a syntax error.
Here's the statement:
DELIMITER $$
CREATE TRIGGER `swtalentbank`.`after_candidate_insert`
AFTER INSERT ON `Candidates` FOR EACH ROW
BEGIN
INSERT INTO useradmin (username, talent)
VALUES (NEW.email, 1);
UPDATE `Candidates` SET UserID = useradmin.userid where useradmin.username = NEW.email;
END
DELIMITER ;
I have a registration form on my site. When a person registers it populates the Candidates table with their profile information.
In the Candidates table, there are various fields, two of them being 'email' and 'UserID'.
UserID is also the PK in 'useradmin', so I'm linking the two up.
So when a user registers, I need to insert a record into 'useradmin' with the email address that's just been used to register, and then update the 'Candidates' table, with UserID that's just been created in 'useradmin'.
I hope this makes sense?
NB. I am changing the delimiter before running the statement.
Besides properly using DELIMITER when creating a trigger you have at least two fundamental issues with your current code:
In MySQL you can't use issue a DML statement (in your case UPDATE) against a table (candidates) on which you defined a trigger (also candidates). Your only option is to use BEFORE trigger and set a value of userid column of a row being inserted to a proper value.
You can't arbitrarily reference a column (useradmin.userid) of a table out of the context like you did in your UPDATE. You didn't joined useradmin table or used it in a subquery.
That being said and assuming that userid in useradmin table is an auto_increment column your trigger might look like this
DELIMITER $$
CREATE TRIGGER after_candidate_insert
BEFORE INSERT ON candidates
FOR EACH ROW
BEGIN
INSERT INTO useradmin (`username`, `talent`) VALUES (NEW.email, 1);
SET NEW.userid = LAST_INSERT_ID();
END$$
DELIMITER ;
Here is SQLFiddle demo
You should use semicolon after end your insert query.
You can use INSERT ... ON DUPLICATE KEY UPDATE syntax for your purpose
try out this...
DELIMITER $$
CREATE TRIGGER `swtalentbank`.`after_candidate_insert`
AFTER INSERT ON `Candidates` FOR EACH ROW
BEGIN
INSERT INTO useradmin (username, talent)
VALUES (NEW.email, 1);
UPDATE `Candidates` SET UserID = useradmin.userid where useradmin.username = NEW.email;
END $$
DELIMITER ;

Adding unique data to a sql table

I am learning about sql databases. I am using mysql.
I have designed the tables, and queries. I am now working on the code to put stuff into the database.
I can not work out how to ensure that a record is unique when I have a text field. I tried to mark the part of the record that was not the pk (primary key) as unique, but when it is text it complains that it is not fixed length. I then played with the idea of conditionals in a stored procedure, but could not get it to work.
DELIMITER $$
DROP PROCEDURE IF EXISTS `experiment1`.`add_zzzz`$$
CREATE PROCEDURE `experiment1`.`add_zzzz` (IN v INT, IN n TEXT)
BEGIN
IF EXISTS (
SELECT value, name
FROM zzzz
WHERE value=v AND name=n
)
THEN
ELSE
INSERT INTO zzzz(value,name)
VALUES v,n;
END IF;
END$$
DELIMITER ;
So anyone know what I am doing wrong?
VARCHAR is not fixed and you can use unique index with it
more on http://www.w3schools.com/sql/sql_unique.asp
you can also use INSERT ignore
http://dev.mysql.com/doc/refman/5.5/en/insert.html