I want to do a stored procedure to add a new customer to a table named customers. I want to define the values but even if I choose to leave a field out that those field will be set to NULL and not to a blank string as it is now in the code. I have been thinking about how I can possibly write an if statement or a loop to check the input values.
I work in MySQL Workbench 8.0 if its to any help.
I did add a screenshot of the staff table under the code.
DROP PROCEDURE IF EXISTS add_customer;
DELIMITER //
CREATE PROCEDURE add_customer
(
in First_name TEXT,
in Last_name TEXT,
in Email VARCHAR(255),
in Adress TEXT,
in Postcode TEXT,
in Country TEXT,
in City TEXT,
in Phone TEXT,
-- in Points DECIMAL(9,2),
in Social_security_no TEXT,
in org_no TEXT,
in memberNO TEXT
)
BEGIN
INSERT INTO customers (id_customer, first_name, last_name, email, adress, postcode, country, city, phone, social_security_no, org_no, memberNO)
VALUES (DEFAULT , first_name, last_name, email, adress, postcode, country, city, phone, social_security_no, org_no, memberNO );
END //
DELIMITER ;
Screenshoot of the customers table
You can use nullif(varName,''). This will return null whn varName field is empty string. Use this on fields you want to:
INSERT INTO customers (id_customer, first_name, last_name, email, adress, postcode, country, city, phone, social_security_no, org_no, memberNO)
VALUES (DEFAULT , nullif(first_name,''), nullif(last_name,''), nullif(email,''), nullif(adress,''), nullif(postcode,''), nullif(country,''), nullif(city,''), nullif(phone,''), nullif(social_security_no,''), nullif(org_no,''), nullif(memberNO ,''));
Related
I have a table with the name users where my userId is primary key and incremental what I am trying to do is write a stored procedure that would accept user data and since userId is incremental it would return the userId created after insertion of that record.
Here is my stored procedure code:
CREATE OR REPLACE PROCEDURE sp_register_new_user
(firstname IN VARCHAR2,
lastname IN VARCHAR2,
phone_name IN VARCHAR2,
user_password IN VARCHAR2,
email_id IN VARCHAR2,
userrole IN NUMBER,
udid IN VARCHAR2,
res OUT NUMBER)
AS
BEGIN
INSERT INTO users (
first_name,
last_name,
login,
isactive,
role_id,
password,
uuid,
phonenumber
) VALUES (
firstname,
lastname,
email_id,
1,
userrole,
user_password,
udid,
phone_name
);
SELECT LAST_INSERT_ID();
END sp_register_new_user;
I took some references where they say I need to write this line to get the value of the last record
SELECT LAST_INSERT_ID();
but I get an error.
Also, I wanted to do this with the help of transactions but am not sure how to achieve it since new to MySQL, can somebody help me solve this problem
If you want the solution in Oracle, You can use RETURNING keyword there to return last inserted ID -
CREATE OR REPLACE PROCEDURE sp_register_new_user (firstname IN VARCHAR,
lastname IN VARCHAR,
phone_name IN VARCHAR,
user_password IN VARCHAR,
email_id IN VARCHAR,
userrole IN NUMBER,
udid IN VARCHAR,
res IN NUMBER
) AS
BEGIN
INSERT INTO users (
first_name,
last_name,
login,
isactive,
role_id,
password,
uuid,
phonenumber
) VALUES (
firstname,
lastname,
email_id,
1,
userrole,
user_password,
udid,
phone_name
) RETURNING id INTO res;
END sp_register_new_user;
I did this
INSERT INTO users (
first_name,
last_name,
login,
isactive,
role_id,
password,
uuid,
phonenumber
) VALUES (
firstname,
lastname,
email_id,
1,
userrole,
user_password,
udid,
phone_name
) RETURNING id INTO res;
and it worked
I have an user table with 19 rows (first row is admin). I need to add more, so I have another database with a table having more than 1.400.000 users.
My table has an "user_id" as primary key, INT(11), no auto-increment. I need to add users starting in row 20, and only "first_name", "last_name" and "email".
My first try:
INSERT INTO mydatabase.users (first_name, last_name, email) SELECT first_name, last_name, email FROM anotherdatabase.users
That gets me a "Field 'user_id' doesn't have a default value".
I understand it is because user_id is primary key and cannot be null. So, again, it is int(11), non auto-increment.
So I want to add 20,21,22,23 and so on, along the other data. I searched a lot for about 5 hours and can´t seem to find anything I can understand.
Thank you in advance.
To get your numbers starting from 20:
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT 19+row_number() over (),
first_name,
last_name,
email
FROM anotherdatabase.users
19+row_number() over ()
'row_number()' = Number of current row within its partition (Mysql documentation)
'over ()' - defines a partition without condition; so in fact counts for the entire table
Details for both can be found under MySQL Window Function concepts and syntax
19+ - ...
Alternatively - if the MySQL version < 8.0:
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT (select 20+count(*)
from anotherdatabase.users u1 where u1.id < u.id) as id,
first_name,
last_name,
email
FROM anotherdatabase.users u
This does rather assume that you have a user_id on the other table as well.
The inner select just counts how many records are in the original database that have a smaller id than the record that is being returned at that point (and adds 20 to have the numbering start at 20).
And a third option (not depending on the existence of user_id):
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT ( #row_num:=#row_num+1 AS user_id,
first_name,
last_name,
email
FROM anotherdatabase.users u,
(SELECT #row_num:=19) var;
I'm not a great fan of this as it involves creation of variables to keep track of the row number.
Write a procedure that use variable. for i < 1400020 , you would need to count the number of rows in anotherdatabase.users then add the figure with 20.
DELIMITER $$
CREATE PROCEDURE insert_test_data()
BEGIN
DECLARE i INT DEFAULT 20;
WHILE i < 1400020 DO
INSERT INTO mydatabase.users (user_id, first_name, last_name, email)
SELECT i,first_name, last_name, email FROM anotherdatabase.users;
SET i = i + 1;
END WHILE;
END$$
DELIMITER ;
CALL insert_test_data();
DROP PROCEDURE insert_test_data;
I found a simpler way, using variables. I still can´t believe it. It worked like a charm
SET #i=19;
INSERT INTO mydatabase.users(user_id, first_name, last_name, email)
SELECT #i:=#i+1,
first_name,
last_name,
email
FROM anotherdatabase.users;
I have created a table called Customers with a CustomerID, Last Name, First Name, Address, and City, but when I tried to use the INSERT INTO to add data and ran the SQL Statement, it gives me an error: "Syntax error in CREATE TABLE statement". Below is the SQL Statement I have so far:
CREATE TABLE Customers
(
CustomerID int,
LastName varchar(50),
FirstName varchar(50),
Address varchar(50),
City varchar(50)
);
INSERT INTO (CustomerID, LastName, FirstName, Address, City)
VALUES ('10001', 'Smith', 'John', '1002 Danville Road', 'Louisville');
You are missing the table name from your INSERT statement:
INSERT INTO Customers (CustomerID, LastName, FirstName, Address, City)
VALUES ('10001', 'Smith', 'John', '1002 Danville Road', 'Louisville');
As to why you got an error pointing to your CREATE TABLE statement (which looks correct), my guess is that Access tried to connect the botched INSERT statement to the create in an effort to parse everything correctly.
I am trying to perform an INSERT INTO .. SELECT .. statement in a stored procedure in phpmyadmin. The statement works perfectly when I run it as SQL, but when I use a stored procedure, it fails without giving an error message.
stored procedure:
IN: v_activation_code varchar 15 utf-8
INSERT INTO tbl_users (username, firstname, name, email, password, status, studnr, address, city, dob, gender)
SELECT username, firstname, name, email, password, status, studnr, address, city, dob, gender
FROM tbl_users_non_activated
WHERE activation_code LIKE 'v_activation_code'
Thanks in advance!
Hello I'm working on a database assignment and I'm stuck on how to do this one stored procedure. Although It works, sort of...
DELIMITER //
CREATE PROCEDURE AddANewCustomer(IN firstName char(20), IN lastName char(20), IN companyName char(45), IN streetAddress char(60), IN city char(30), IN province char(45), IN postalCode char(6), IN phoneNumber int(10))
BEGIN
DECLARE PersonID INT;
SELECT idPerson FROM Persons WHERE Persons.firstName = firstName AND Persons.lastName = lastName INTO PersonID;
IF PersonID IS NULL THEN
INSERT INTO Persons(firstName, lastName, streetAddress, city, province, postalCode, phoneNumber) VALUES (firstName, lastName, streetAddress, City, Province, postalCode, phoneNumber);
SELECT idPerson FROM Persons WHERE firstName = firstName AND lastName = lastName INTO PersonID;
END IF;
INSERT INTO Customers(idCustomer, companyName) VALUES (Last_Insert_ID(), companyName);
END //
DELIMITER ;
Basically I'm working with Super/Sub types. I want to take the information from the user and then update my parent table (Persons) and pass on the remaining information to my child table (Customers). idPerson is the auto-incrementing PK for Persons table, and I want to use that as a PK/FK for the Customers table's id, idCustomer.
If I run the procedure once, it'll spit out an error 'Result consist of more than one row' and only the Parent table gets updated... But if I run it again, it'll update the Child table properly. Which makes me think that the Last_Insert_ID() parameter is null the first time around and the idPerson only gets updated after the procedure is done.
I've researched for a fix all night and now I'm absolutely stumped on how to solve this.
Ouch.
Basically I'm working with Super/Sub
types.
I don't think so, but I could be wrong. Customer usually describes a relationship between two parties, one a buyer and the other a seller.
If I run the procedure once, it'll
spit out an error 'Result consist of
more than one row'
What do you think that means? Does this query return any rows?
SELECT lastname, firstname, count(*)
FROM Persons
GROUP BY lastname, firstname
HAVING count(*) > 1;
You check for a NULL id number,
IF PersonID IS NULL THEN
but you ignore the possibility that your SELECT statement might return 2 or 3 or 42 different id numbers, all for people who have the same first and last name. Is that wise? Phrased another way, do you have a UNIQUE constraint on {firstname, lastname}?
If PersonID is null, you insert a row into Persons, which sets a value that LAST_INSERT_ID() can return. But your second INSERT tries to use LAST_INSERT_ID() without regard to whether a row was previously inserted into Persons.
Finally, you have two slightly different versions of
SELECT idPerson
FROM Persons
WHERE Persons.firstName = firstName
AND Persons.lastName = lastName
INTO PersonID;
I'm pretty sure you need one at most.