I am trying to create an trigger for an audit log, where after an insert into manageMemberLog and the action column is equal to CREATE, then insert the associate columns of users table and then grab the select the newly created row and grab the userID and then insert the rest of the data into profile, but I get this error msg when I tried to submit the query.
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'END' at line 9
Line 9 = END IF;
I tried carefully re-typing what I wrote but same error msg.
UPDATE: used the formatting and it says WHERE userID = #newUserID is the error, which i still don't understand as I grab the data from select and set the value into #newUserID.
DELIMITER $$
CREATE TRIGGER usersDB_ai AFTER INSERT
ON manageMemberLog
FOR EACH ROW
IF NEW.action = 'CREATE' THEN
INSERT INTO users (firstName, lastName, userName, email, pwd) VALUES (NEW.firstName, NEW.lastName, NEW.userName, NEW.email, NEW.pwd);
SET #newUserID := (SELECT userID FROM users WHERE userName = NEW.userName AND email = NEW.email);
UPDATE profiles SET rankID = NEW.rankID WHERE userID = #newUserID;
END IF;
END$$
DELIMITER ;
The related tables:
CREATE TABLE `users` (
`userID` int(11) NOT NULL,
`firstName` varchar(128) NOT NULL,
`lastName` varchar(128) NOT NULL,
`userName` varchar(128) NOT NULL,
`email` varchar(128) NOT NULL,
`pwd` varchar(128) NOT NULL
)
DELIMITER $$
CREATE TRIGGER `userCreated` AFTER INSERT ON `users` FOR EACH ROW BEGIN
INSERT INTO profiles (userID) VALUES(NEW.userID);
END
$$
DELIMITER ;
CREATE TABLE `profiles` (
`profileID` int(11) NOT NULL,
`userID` int(11) NOT NULL,
`rankID` int(11) NOT NULL,
...
)
CREATE TABLE `manageMemberLog` (
`manageMemberLogID` int(11) NOT NULL,
`manageDate` datetime NOT NULL,
`managerID` int(11) DEFAULT NULL,
`action` varchar(6) CHARACTER SET utf8mb4 NOT NULL,
`userID` int(11) DEFAULT NULL,
`firstName` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`lastName` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`userName` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`email` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`pwd` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`rankID` int(11) NOT NULL
)
Can anyone help thanks in advance!
Silly Me, so what went wrong is I forgot to write "BEGIN" after FOR EACH ROW and does not involve any of the error that it says. Error messages are sometimes not reliable but I guess it did help by say END. A better error message is you can't end when it never began.
so correct query is:
DELIMITER $$
CREATE TRIGGER usersDB_ai AFTER INSERT
ON manageMemberLog
FOR EACH ROW BEGIN
IF NEW.action = 'CREATE' THEN
INSERT INTO users (firstName, lastName, userName, email, pwd) VALUES (NEW.firstName, NEW.lastName, NEW.userName, NEW.email, NEW.pwd);
SET #newUserID := (SELECT userID FROM users WHERE userName = NEW.userName AND email = NEW.email);
UPDATE profiles SET rankID = NEW.rankID WHERE userID = #newUserID;
END IF;
END$$
DELIMITER ;
Related
It give me error example image at below:
Trigger code:
CREATE OR REPLACE TRIGGER InsertNewStaffs
BEFORE INSERT ON Staffs
FOR EACH ROW
ENABLE
DECLARE
v_user varchar(255);
v_date varchar(255);
v_Staffs_ID Staffs.Staffs_ID%TYPE;
v_Staffs_Name Staffs.Staffs_Name%TYPE;
v_Staffs_Contact_Number Staffs.Staffs_Contact_Number%TYPE;
v_Staffs_Email Staffs.Staffs_Email%TYPE;
v_Orders_ID Staffs.Orders_ID%TYPE;
v_count INTEGER;
BEGIN
SELECT count(*) INTO v_count FROM Staffs
WHERE Staffs_ID = v_Staffs_ID OR
Staffs_Name = v_Staffs_Name OR
Staffs_Contact_Number = v_Staffs_Contact_Number OR
Staffs_Email = v_Staffs_Email;
IF v_count > 0 THEN
RAISE_APPLICATION_ERROR(-20000, 'Oops, some data is already exists. Please try again...');
DBMS_OUTPUT.PUT_LINE('Oops, some data is already exists. Please try again...');
SELECT user, TO_CHAR(sysdate, 'DD/MON/YYYY HH24:MI:SS') INTO v_user, v_date FROM dual;
ELSE
INSERT INTO Staffs(Staffs_ID, Staffs_Name, Staffs_Contact_Number, Staffs_Email, Orders_ID)
VALUES(v_Staffs_ID, v_Staffs_Name, v_Staffs_Contact_Number, v_Staffs_Email, v_Orders_ID);
DBMS_OUTPUT.PUT_LINE('One Row Inserted By ' || v_user || CHR(10));
DBMS_OUTPUT.PUT_LINE('Inserted data at ' || v_date);
INSERT INTO monitorInsertStaffs(user_name, entry_date, operation)
VALUES(v_user, v_date, 'Insert');
END IF;
END;
/
My Table:
CREATE TABLE Staffs(
Staffs_ID char(20) NOT NULL,
Staffs_Name varchar(255) NOT NULL,
Staffs_Contact_Number varchar(50) NOT NULL,
Staffs_Email varchar(255) NOT NULL,
Orders_ID char(20),
PRIMARY KEY (Staffs_ID),
FOREIGN KEY (Orders_ID) REFERENCES Orders(Orders_ID)
);
CREATE TABLE Orders(
Orders_ID char(20) NOT NULL,
Order_Date DATE NOT NULL,
Order_Status varchar(255) NOT NULL,
Order_Quantity int NOT NULL,
Order_TotalAmount NUMERIC(10,2) NOT NULL,
Order_TotalPrice NUMERIC(10,2) NOT NULL,
PRIMARY KEY (Orders_ID),
Pets_Products_ID char(20),
CustomerID char(20),
FOREIGN KEY (Pets_Products_ID) REFERENCES Pets_Products(Pets_Products_ID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
I try to insert data and if the data has existed it will show RAISE_APPLICATION_ERROR(-20000, 'Oops, some data is already exists. Please try again...'); but it didn't show the message and also cannot insert data when no exists the data.
I don't know where is error code that I find.
The whole concept is just wrong.
you've based trigger on a table into which you're just inserting a row (staffs)
then you're selecting from the same table (it'll raise the mutating table error if you try to insert more than a single row)
the where clause uses local variables that have no values
insert into staffs cause the same trigger to fire over and over again, until Oracle concludes that that's enough and raises the error
Don't use a trigger. Use UNIQUE constraints:
CREATE TABLE Staffs(
Staffs_ID char(20) NOT NULL,
Staffs_Name varchar(255) NOT NULL,
Staffs_Contact_Number varchar(50) NOT NULL,
Staffs_Email varchar(255) NOT NULL,
Orders_ID char(20),
PRIMARY KEY (Staffs_ID),
UNIQUE (Staffs_Name),
UNIQUE (Staffs_Contact_Number),
UNIQUE (Staffs_Email),
FOREIGN KEY (Orders_ID) REFERENCES Orders(Orders_ID)
);
(However, you should also consider whether your business requirements make sense or if you can have multiple staff members called Jane Smith or if you can have two staff members who share an office with the same telephone number?)
If you want to use a logging table then use an autonomous transaction to just insert into that table:
CREATE OR REPLACE TRIGGER InsertNewStaffs
BEFORE INSERT ON Staffs
FOR EACH ROW
ENABLE
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO monitorInsertStaffs(
user_name, entry_date, operation
) VALUES(
:NEW.Staffs_ID, SYSDATE, 'Insert'
);
COMMIT;
END;
/
db<>fiddle here
create table Employees
(
EmployeeID INT IDENTITY (1,1) PRIMARY KEY NOT NULL,
EmployeeName VARCHAR(255) NOT NULL,
EmployeeUsername VARCHAR(255) NOT NULL,
EmployeeEmail VARCHAR(255) NOT NULL,
GroupID INT FOREIGN KEY REFERENCES TypeOfGroup(GroupID),
Password VARCHAR(255) NOT NULL
);
create table TypeOfGroup
(
GroupID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
TypeGroup VARCHAR(255) NOT NULL,
Permission CHAR(1) NOT NULL
);
Question: I have a foreign key and wanted to make a connection with another table as I do this to insert into.
My foreign key is 'GROUPID'.
Try this...
insert into TypeOfGroup( TypeGroup, Permission) values ('hr', 1)
"this 1 is used for bit which is a data type in sql server 1 for true and 0 for false"
insert into Employees (EmployeeName, EmployeeUsername, EmployeeEmail,
GroupID, Password) values ('bruno', 'bruno', 'bruno#gmail.com', 1, 'urPassword')
and 1 in the 2nd query is primary of typeofgroup table.
I am importing database and i got an error
1062 - Duplicate entry '1' for key PRIMARY.
i tried to upload table individually But it gives me error for those table which have at least one row.
i don't want to delete any record of any table.
here is one table which is giving error.
CREATE TABLE IF NOT EXISTS `wpbeta_aff_affiliates` (
`affiliate_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`email` varchar(512) DEFAULT NULL,
`from_date` date NOT NULL,
`thru_date` date DEFAULT NULL,
`status` varchar(10) NOT NULL DEFAULT 'active',
`type` varchar(10) DEFAULT NULL,
PRIMARY KEY (`affiliate_id`),
KEY `affiliates_afts` (`affiliate_id`,`from_date`,`thru_date`,`status`),
KEY `affiliates_sft` (`status`,`from_date`,`thru_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `wpbeta_aff_affiliates`
--
INSERT INTO `wpbeta_aff_affiliates` (`affiliate_id`, `name`, `email`, `from_date`, `thru_date`, `status`, `type`) VALUES
(1, 'Direct', NULL, '2013-07-03', NULL, 'active', 'direct');
You do not need to specify the record id (with the exception of some circumstances when you need to keep the connection between records in different tables). Try using this query:
INSERT INTO wpbeta_aff_affiliates (name, email, from_date, thru_date, status, type) VALUES ('Direct', NULL, '2013-07-03', NULL, 'active', 'direct');
I have two tables auth_user and temp
These are their schema:
CREATE TABLE "auth_user" (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(30) NOT NULL UNIQUE,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL,
"email" varchar(75) NOT NULL,
"password" varchar(128) NOT NULL,
"is_staff" bool NOT NULL,
"is_active" bool NOT NULL,
"is_superuser" bool NOT NULL,
"last_login" datetime NOT NULL,
"date_joined" datetime NOT NULL
);
CREATE TABLE "temp" ( "id" integer, "username" varchar(30));
I want the id fields in the auth_user table to be updated to the id field of the temp table provided the username is the same. How can I achieve this?
I tried this SQL:
Update auth_user set id=(select temp.id from temp where temp.username=auth_user.username);
But I get this error:
Error: datatype mismatch
I found this question Update table values from another table with the same user name
It is similar to my question. Looking at the answer in that page, I tried this query
update auth_user set id=(select temp.id from temp where temp.username=auth_user.username) where exists (select * from temp where temp.username=auth_user.username);
and it works great. Same as my query in the question but with just an extra where clause. I don't get the Error: datatype mismatch now (but I don't know the exact reason why).
.net 2.0 and C# - I am inserting the row in to mysql using a stored procedure, but when I tried to insert data from two clients at same time, I found only one row is inserted and not both. I am unable to get the error. How can I tune the DB or my code to insert all the data and no threading is appreciated
Here goes my table
delimiter $$
CREATE TABLE `tblemployee` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`EmpID` int(11) NOT NULL,
`FedTaxID` varchar(9) CHARACTER SET utf8 NOT NULL,
`FirstName` varchar(20) DEFAULT NULL,
`MiddleInitial` varchar(20) DEFAULT NULL,
`LastName` varchar(20) DEFAULT NULL,
`SSN` decimal(9,0) NOT NULL,
`DateOfBirth` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`MaritalTypeID` varchar(4) CHARACTER SET utf8 DEFAULT NULL,
`EmployeeTypeID` varchar(1) CHARACTER SET utf8 DEFAULT NULL,
`EmploymentStatusTypeID` varchar(1) CHARACTER SET utf8 DEFAULT NULL,
`HireDate` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`EmployeeWorkLocation` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`RegularPay` double DEFAULT NULL,
`HourlyRate` double DEFAULT NULL,
`OtherHoursRate` double DEFAULT NULL,
`StartDate` date NOT NULL,
`EndDate` date NOT NULL,
`PayFrequencyTypeID` varchar(50) DEFAULT NULL,
PRIMARY KEY (`EmpID`,`FedTaxID`),
UNIQUE KEY `SSN_UNIQUE` (`SSN`),
KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=385 DEFAULT CHARSET=latin1$$
Here goes my stored procedure:
CREATE DEFINER=`root`#`%` PROCEDURE `uspEmployeeAdd`(_EmpID int,_FedTaxID varchar(9),_SSN decimal(9,0),_DateOfBirth varchar(50),_MaritalTypeID varchar(2),_EmployeeTypeID varchar(1),_EmploymentStatusTypeID varchar(1),_HireDate varchar(50),_EmployeeWorkLocation varchar(30),_PayFrequencyType varchar(2),_RegularPay double,_HourlyRate double,_OtherHoursRate double)
BEGIN
insert delayed into tblEmployee(EmpID, FedTaxID, SSN, DateOfBirth, MaritalTypeID, EmployeeTypeID, EmploymentStatusTypeID, HireDate, EmployeeWorkLocation, PayFrequencyType, RegularPay, HourlyRate, OtherHoursRate)
values(_EmpID, _FedTaxID, _SSN, _DateOfBirth, _MaritalTypeID, _EmployeeTypeID, _EmploymentStatusTypeID, _HireDate, _EmployeeWorkLocation, _PayFrequencyType, _RegularPay, _HourlyRate, _OtherHoursRate);
END
here goes my .net code
public bool Adding()
{
m_bFlag = false;
if (m_oConn.State != ConnectionState.Open)
{
m_oConn.Open();
}
MySqlTransaction otrans = new MySqlTransaction();
otrans=m_oConn.BeginTransaction();
m_oCmd = new MySqlCommand(StoredProcNames.EmployeeDetails_uspEmployeeDetailsInsert, m_oConn);
m_oCmd.CommandType = CommandType.StoredProcedure;
m_oCmd.Parameters.AddWithValue("_EmpID", EmpID);
m_oCmd.Parameters.AddWithValue("_FedTaxID", FedTaxID);
m_oCmd.Parameters.AddWithValue("_FirstName", FirstName);
m_oCmd.Parameters.AddWithValue("_MiddleInitial", MiddleInitial);
m_oCmd.Parameters.AddWithValue("_LastName", LastName);
m_oCmd.Parameters.AddWithValue("_SSN", SSN);
m_oCmd.Parameters.AddWithValue("_MaritalTypeID", Gender);
m_oCmd.Parameters.AddWithValue("_HireDate", HireDate);
m_oCmd.Parameters.AddWithValue("_DateOfBirth", DateOfBirth);
m_oCmd.Parameters.AddWithValue("_PayFrequencyTypeID", PayFrequencyTypeID);
m_oCmd.Parameters.AddWithValue("_StartDate", StartDate);
m_oCmd.Parameters.AddWithValue("_EndDate", EndDate);
try
{
if (m_oCmd.ExecuteNonQuery() > 0)
{
m_bFlag = true;
otrans.Commit();
}
}
catch (MySqlException mse)
{
throw mse;
otrans.Rollback();
}
finally
{
m_oConn.Close();
}
return this.m_bFlag;
}