Im trying to make an stored Procedure that makes an insert into tables.
The insert effects two tables and there is an FK between them.
CREATE PROCEDURE `db`.`add_user_hr` (
IN in_Pass VARCHAR(45),
IN in_Value VARCHAR(45),
IN in_HR_ID INT,
)
BEGIN
INSERT INTO HR
(
Value
)
VALUES
(
in_Value
);
INSERT INTO User
(
Password,
HR_idHR
)
VALUES
(
in_Pass,
(Get the ID from HR)
);
END
How do I make sure that the correct id gets into User. And
if there is a error in the insert into HR, who do I make
sure it dosent tyr to make an insert into User? Ive
looked into "commit" but don't know how it's used.
Or is there a better way to do this?
In this example I have table UserType. Is this needed to
to find out witch type of user it is later on? And
how do I user this in the insert, select procedure in the
future?
Thx for all the help!
If PK (primary key) has AUTO_INCREMENT options than you can do something like this:
declare value_id_v INT;
insert into hr(value) values(value_in);
set value_id_v = last_insert_id();
Now you can use value_id_v to do inserts. Here is the link to read about this function LAST_INSERT_ID
Related
after searching for a while I could not find a way to add rows in bulk by passing in argument for example a list of values. I know that it is possible to create a for loop, but it would insert each value separately n times, which I assume is bad performancewise. Here is a sample of what I have
CREATE PROCEDURE \`spLogAdd\`(
IN \`userId\` VARCHAR(255),
IN \`isActive\` BIT,
IN \`valueDatetime\` DATETIME,
IN \`valueId\` INT
)
BEGIN
INSERT INTO log_table (user_id, is_active, value_datetime, valueId)
VALUES (\`userId\`, \`isActive\`, \`valueDatetime\`, \`valueId\`);
END;
What I would like to have is a list of userIds('1,2,3,4,5,6') to insert multiple rows with 1 then 2 and so on at once. Other arguments do not need to change. If there is any neat way, please help me to do that.
CREATE PROCEDURE \`spLogBulkAdd\`(
IN \`userId\` VARCHAR(255),
IN \`isActive\` BIT,
IN \`valueDatetime\` DATETIME,
IN \`valueId\` INT
)
BEGIN
INSERT INTO log_table (user_id, is_active, value_datetime, valueId)
VALUES (\`userId\`, \`isActive\`, \`valueDatetime\`, \`valueId\`);
END;
I'm creating a stored procedure to insert data into three different tables.
Here is my code:
/*------------------------- Procedure for owner to submit his property -------------------------*/
DELIMITER //
CREATE PROCEDURE SubmitProperty (
IN input_property_owner_id INT,
IN input_property_type_id INT,
IN input_address VARCHAR(255),
IN input_zip_code VARCHAR(255),
IN input_area_m2 INT,
IN input_price_€ INT
)
BEGIN
INSERT INTO property (property_owner_id, property_type_id, address, zip_code, area_m2, price_€)
VALUES
(input_property_owner_id, input_property_type_id, input_address, input_zip_code, input_area_m2, input_price_€);
INSERT INTO survey (property_id, cas_eval_id, checksum_xxx)
VALUES
(property.id, 'CAS-XXX-YYYY', property.id % 1000);
INSERT INTO survey_question_answer (survey_id, question_id)
SELECT property_type_question.question_id
FROM property_type_question
WHERE property_type_question.property_type_id = input_property_type_id
VALUES
(survey.id, property_type_question.question_id);
END //
DELIMITER ;
The first 2 inserts work properly.
However, I get an error in the 3rd insert (around the area between the very last "FROM" and "VALUES").
Here is a picture of the error message:
Could you guys help me figure this out?
Thanks!
Is it because you're trying to insert into two columns, but are only selecting one?
INSERT INTO survey_question_answer (survey_id, question_id)
SELECT property_type_question.question_id
Is survey_id an identity column? If no, you need to bring in the survey_id from survey table and add that to your select clause:
INSERT INTO survey_question_answer (survey_id , question_id)
SELECT survey.id, property_type_question.question_id
FROM property_type_question
//Join here with your survey table
WHERE property_type_question.property_type_id = input_property_type_id;
I want to create a procedure that creates a course for a user this takes one parameter that is userid and the other value will be selected from tbl_chapter.there are 27 chapters that are going to be selected and 27 inserts will be executed .insert is going to be like INSERT INTO tbl_user_chapter(user_id,chapter_id) VALUEs (9 , 1),(9,2),(9,3),....
I want something like this:
CREATE PROCEDURE createCourse (IN userid_param int)
BEGIN
INSERT INTO tbl_user_chapter(tbl_user_chapter.user_id,tbl_user_chapter.chapter_id) VALUE(userid_param , SELECT id FROM tbl_chapter)
END
SELECT id FROM tbl_chapter will be multiple rows.
I know this is wrong and I need help.
if there is a better way to do this please let me know.
If the select does not return one row, then don't use the VALUES( ) syntax. Use INSERT ... SELECT syntax:
CREATE PROCEDURE createCourse (IN userid int)
BEGIN
INSERT INTO tbl_user_chapter(user_id,chapter_id)
SELECT userid, id FROM tbl_chapter;
END
Make sure userid does NOT conflict with a column of the same name in your tbl_chapter table. If a column exists with that name, you should change the IN parameter of the stored procedure.
I have a requirement where in my sql a column 2 would always have the uppercase value that is column 1,
Not sure ow to do this in mysql. I want to do something like this , I know the syntax below is incorrect but writing some psuedo code as to make it clear what I am trying to achieve
create table sakila.testupper(name varchar(50),
uppername varchar(50) not null default as select upper(#name));
I believe you could accomplish this across most version of MySQL with a trigger on insert or update: http://dev.mysql.com/doc/refman/5.7/en/triggers.html
The syntax you're after looks like this: "create table sakila.testupper (name varchar(50), uppername varchar(50) generated always as (upper(name)));". However, you'd need a recent release of MySQL version 5.7.
You can't have the table do this automatically but you can create a trigger for all future INSERTs. With a trigger you will need to maintain a separate table.
drop table if exists p;
drop table if exists q;
create table q (name nvarchar(59),uppername nvarchar(59));
create table p (name nvarchar(59));
create trigger trig_thing after insert on p
for each row
begin
insert into q set name = new.name, uppername = upper(new.name);
end;
insert into p (name) values ('Some nice gentleman');
insert into p (name) values ('A sweet old lady');
select * from q;
Your original table will keep only the name, but each insert will cause a trigger to insert the same data into your new table with name and uppername.
If you already have names stored in a table you should insert into your second table to get them in line before you set up the trigger:
insert into q name, upper(name) from p;
here is a functional example
I need to do this: On inserted record I need to store Inserted item identity and selected item identity. (Example below)
I'm using after insert trigger (basically I copy one row from one table into another and do some more modifications.
I have a table parameter like this:
DECLARE #Tempequipment TABLE
(Equipment_Id int,
DefaultEquipment_Id INT)
Then I insert into table like this:
INSERT INTO dbo.tblEquipmentType
( Name, EquipmentType_Id)
SELECT name,(SELECT Equiment_Id FROM INSERTED)
FROM dbo.tblDefaultEquipmentType
This works fine!
What I need to do is: I need to insert into #TempEquipment EquipmentTypeId's that were just ineserted (can be more than one) and DefaultEquipmentTypeId's that were just copied.
I was thinking about doing something like:
INSERT INTO dbo.tblEquipmentType
( Name, EquipmentType_Id)
Output EquipmentTypeId, DefaultEquipmentTypeId into #TempEquipment
SELECT name,(SELECT Equipment_Id FROM INSERTED)
FROM dbo.tblDefaultEquipmentType
but of course this is not going to work, since it cannot get values from select statement, and not written correctly.
Any help is appreciated!
UPDATE:
I have an Item. Item can be built on different equipment. Equipment has types (foreign key. And equipmentType has attributes (foreignkey).
So this mean that we have four tables Item->Equipment->EquipmentType->EquipmentAttribute.
I need to store default EquipmentTypes and default EquipmentAtrributes for that type.
So I also got these replationship: Equipment->DefaultEquipmentType->DefaultEquipmentAttribute.
Now, When I insert new Item and select an equipment I want to copy defaults over to real tables (EquipmentType, EquipmentAttribute).
Is it clear at least a little?
Aside from how you're trying to do this (which isn't working), what specifically are you trying to do?
It may be that this can be resolved by changing / normalizing your paradigm, instead of some kind of exotic code. For example, it looks odd to have a customers table with an orderID field in it. Unless your customers only ever order one thing... I would have expected to see a customers table, an items table, and then an orders table that joined customers with items.
Hope that makes sense -- but anyway, if not, can you post your table structure, and maybe be a little more clear on what you know ahead of time (e.g., I imagine you know who your customers are, and what they ordered...before you do the insert...yes?)
For an INSERT statement you can only access the columns which are in the insert column list, so the solution is to rewrite the statement as a MERGE statement which can access all the columns including columns which are in the INSERT target table for instance IDENTITY columns.
In the demo I've used dbo.INSERTED to emulate the virtual table INSERTED from the trigger.
USE master
GO
IF DB_ID('MergeOutputExample') IS NOT NULL
DROP DATABASE MergeOutputExample
GO
CREATE DATABASE MergeOutputExample
GO
USE MergeOutputExample
GO
DECLARE #Tempequipment TABLE
(EquipmentId int,
DefaultEquipmentId INT,
ID int);
CREATE TABLE dbo.INSERTED
(
EquipmentTypeId int PRIMARY KEY
);
CREATE TABLE dbo.tblEquipmentType
(
ID int IDENTITY(1,1),
Name varchar(50),
EquipmentTypeId int PRIMARY KEY
);
CREATE TABLE dbo.tblDefaultEquipmentType
(
EquipmentTypeId int,
DefaultEquipmentTypeId int IDENTITY(1,1) PRIMARY KEY,
Name varchar(50)
);
INSERT dbo.inserted
(
EquipmentTypeId
)
VALUES (1);
INSERT dbo.tblDefaultEquipmentType
(
EquipmentTypeId,
Name
)
VALUES (
1,
'Hammer'
);
MERGE dbo.tblEquipmentType AS ET
USING (
SELECT DE.EquipmentTypeId,
DE.DefaultEquipmentTypeId,
DE.Name
FROM dbo.tblDefaultEquipmentType DE
INNER JOIN dbo.INSERTED I
ON DE.EquipmentTypeId = I.EquipmentTypeId
) AS DET
ON ET.EquipmentTypeId = DET.EquipmentTypeId
WHEN NOT MATCHED BY TARGET
THEN INSERT
(
Name,
EquipmentTypeID
)
VALUES
(
DET.Name,
DET.EquipmentTypeID
)
OUTPUT DET.EquipmentTypeId,
DET.DefaultEquipmentTypeId,
INSERTED.ID
INTO #Tempequipment;
SELECT *
FROM #Tempequipment;
SELECT *
FROM dbo.tblEquipmentType;