I have a database table in mysql
create table userstable
(
id int not null auto_increment,
name varchar(80) not null,
username varchar(80) not null,
primary key(id)
);
How to add new row in mysql database, so that username will be 'name'+('id'*100)
Example :
ID name username
1 A A100
2 B B200
3 C C300
4 user user400
You need trigger for that process. Create the following trigger
CREATE TRIGGER username_change
BEFORE INSERT ON userstable
FOR EACH ROW
BEGIN
SET NEW.username = CONCAT(NEW.name,(NEW.id*100));
END
OR
INSERT INTO userstable (id,name, username) VALUES (2, 'B', CONCAT(name,(id*100)));
Try this.
You'll need to write a trigger or update the field after insertion. A similar question provides more insight:
Can you access the auto increment value in MySQL within one statement?
As #ArunKrish correctly pointed out, you may use TRIGGER to update the data as part of the insert. Another option is to use view:
CREATE VIEW v1 AS
SELECT id,name,CONCAT(name,id*100) AS username FROM userstable;
You may also use the query as-is, without view:
SELECT id,name,CONCAT(name,id*100) AS username FROM userstable;
Related
I have 2 tables with different structures.
CREATE TABLE test1
(
id INTEGER PRIMARY KEY,
EmpName VARCHAR(50),
Empid INTEGER
);
CREATE TABLE test2
(
Empid INTEGER PRIMARY KEY,
EmpFName VARCHAR(50),
EmpLName VARCHAR(50)
);
Is there a way to insert rows from test2 table into test1? If the row exists in test1 it should update the row as well. I think it's possible with Merge statement but it's not available for MySQL. Is there a similar function like this in MySQL?
I've looked into INSERT ... ON DUPLICATE KEY UPDATE but the tables should have the same primary keys.
I think this can help you.
Create Trigger to detect when insert/update data in your table test2.
Inside Trigger use REPLACE INTO to change data in your table test1.
Please check this link for additional of REPLACE INTO command.
Is there a way to insert rows from test2 table into test1? If the row exists in test1 it should update the row as well
UPDATE test1
JOIN test2 USING (Empid)
SET test1.EmpName = CONCAT_WS(' ', EmpFName, EmpLName)
Pay attention - EmpName max length is 50 whereas total length of combined name may be up to 50+1+50=101, so the combined value may be truncated. Increase max length for EmpName.
If you need to perform this operation automatically when the data in test2 is inserted/updated then use AFTER INSERT and AFTER UPDATE triggers, like
CREATE TRIGGER tr
AFTER INSERT -- and the same trigger on AFTER UPDATE event
ON test2
FOR EACH ROW
UPDATE test1
SET EmpName = CONCAT_WS(' ', NEW.EmpFName, NEW.EmpLName)
WHERE test1.Empid = NEW.Empid;
Here is my table schema
MariaDB [a1]> show create table bad_numbers_final;
+-------------------+-------------------------------------------
| Table | Create Table
+-------------------+-------------------------------------------
| bad_numbers_final | CREATE TABLE bad_numbers_final (
id int(11) NOT NULL AUTO_INCREMENT,
phone varchar(255) NOT NULL,
phone_count varchar(255) DEFAULT NULL,
PRIMARY KEY (id,phone)
) ENGINE=InnoDB AUTO_INCREMENT=126956 DEFAULT CHARSET=latin1 |
+-------------------+-------------------------------------------
Now I want to insert a phone if that same number exists in the table then it just increase the phone_count otherwise add a new row in the table . So for that I use a stored procedure and write in it
BEGIN IF ('phone'='10083121224') THEN UPDATE bad_numbers_final SET phone_count= phone_count+10 WHERE 'phone'='10083121224' ;
ELSE INSERT INTO bad_numbers_final (phone,phone_count) VALUES ('10083121224',10);END IF;END
But when I execute this procedure it always insert a new row in the table in place of increasing the phone_count because the value ofphone which I'm inserting that value is already in the table so it just have to increase the phone_count but its not doing so. Please give any suggestions. Thanks in advance.
In 'phone'='10083121224' you are comparing two different strings. You should compare phone='10083121224'.
Also, phone_count is a varchar(255). No. It should be a number (int
or whatever) It doesnt make sense as varchar.You would concatenate "10" as a string this way. So if you had "0" before, after, you will have "010" and then "01010" and so on.
Then you can do this:
UPDATE bad_numbers_final SET phone_count= phone_count+10 WHERE phone='10083121224' ;
Where instead of '10083121224' my guess is that you will need to place a parameter for the procedure.
Also perhaps you want to change the phone datatype as number as well
I've got an answer of my own question i.e. I've done some changes in my if condition i.e.
BEGIN
IF (select phone from bad_numbers_final WHERE phone='10083121224') THEN
UPDATE bad_numbers_final SET phone_count= phone_count+10 WHERE phone='10083121224';
ELSE INSERT INTO bad_numbers_final (phone,phone_count) VALUES ('10083121224',10);
END IF;
END
the problem is that my if condition isn't working because it is not getting from where the field phone is coming and it is just about to insert one sub query inside the if condition and here it is working fine and thank you for all of your suggestions.
I'm trying to create a trigger which will capture any event that will occur when I update any column in the table before and after updating, let's say I have 4 columns:
first_name address city country
Let's say I edited first_name lets say Jack to Henk.
It should insert in another table the command (i.e. update) ,time , description but inside the description I want it to write Jack was changed to John by current user(i.e using the current-user () function),if it is a city being updated from Mechinkova to Tostov, it should do the same do with other columns.
I know I want to have to add the concat function inside the trigger, I want it to be like this for example:
DROP TRIGGER IF EXISTS adminpanel.soft//
CREATE TRIGGER adminpanel.soft BEFORE UPDATE ON adminpanel.aggrement
FOR EACH ROW
BEGIN
INSERT INTO adminpanel.aggretrigger(cmd, time, cmd_user, last_name, city) VALUES("INSERT", NOW(), CURRENT_USER(), new.last_name, new.city);
END
//
What you are asking for is an audit trigger. It is very easy to implement.
Let us first slightly modify your main table. Let's add a field id of integer datatype as the primary key to the table, so your table would look like:
tablename
( id integer PK
, first_name varchar
, address varchar
, city varchar
, country varchar
)
Now, you will need a table, say UNIVERSAL_AUDIT_ENTRY table that will store the changes made to the data in your schema.
From what experience I have, I suggest you create this table as follows:
universal_audit_entry
( universal_audit_entryid integer PK
, table_name varchar -- captures the name of the table
, column_name varchar -- captures the name of the column
, entry_type varchar -- captures the event, e.g., 'INSERT' or 'UPDATE'
, primary_key_value integer -- captures, e.g., the value in tblename.id
, from_str varchar -- captures the value that was present before
, to_str varchar -- captures the value that was changed into
, timestamp datetime -- captures the timestamp of the event
, username varchar -- captures the name of user
)
Now with the universal_audit_entry table ready, your trigger should look somewhat like:
CREATE TRIGGER adminpanel.soft
BEFORE UPDATE ON adminpanel.aggrement
FOR EACH ROW
BEGIN
IF UPDATING(first_name) THEN
INSERT INTO universal_audit_entry VALUES
( 123 -- example for universal_audit_entryid
, 'TABLENAME'
, 'FIRST_NAME'
, 'UPDATE'
, new.id
, old.first_name
, new.first_name
, current_timestamp()
, current_user);
END IF;
END;
//
You can use similar logic to audit more columns in the same table and other tables also.
Note:
This code is not tested. I have added it here only for illustration purposes. This code for trigger is not supposed to be used directly.
new and old are the pseudo-records that are generated during an update statement. These records correspond to the rows that are being updated. :new means the row after the update statement runs and :old means the row before the update statement runs. This works in Oracle. Kindly make sure if it works in MySQL also.
EDIT
You can read more about MySQL triggers here. Read more about audit trail here and this SO question.
i have an situation where i have a following table.
create table Bulk_Data
(
id int identity(1,1),
UserName varchar(100) not null default 'default value ',
iPartitionID int null
)
also i have an Insert trigger on Bulk_Data.
create trigger dbo.Bulk_Data_IU on Bulk_Data
AFTER INSERT
AS Begin
Merge Bulk_Data p1
using Bulk_Data p2 on p1.id = p2.id
when matched then
update set p1.iPartitionID = right(p2.id,1);
end
condition in above table is like
i have 3 column which are not depended on any values.
1] id is identity auto increment column
2] UserName is set to be default values
3] iPartitionID is based on insert in Trigger.
so my question is how should i insert the records say suppose i do not required
to insert any values in #2 i.e. in column 2 so how should i fire the insert command on table.
because insert command is important for me as i have created Insert trigger.
when i run
insert Bulk_Data(UserName) values('Suraj Sheikh')
it works fine but what if i don't want to insert any UserName.
is this possible ?
please help me out here.
You can use a computed column instead of a trigger that updates all rows for each insert.
create table Bulk_Data
(
id int identity(1,1),
UserName varchar(100) not null default 'default value ',
iPartitionID as id % 10 persisted
)
Use "Instead OF" trigger rather than using "AFTER INSERT" trigger.
INSTEAD-OF triggers are very powerful objects in SQL Server. They allow the developer to divert the database engine to do something different than what the user is trying to do.
In this way, when an insert query is fired on that table, insertion will not happen and whatever statements are written in trigger will actually applied to db.
Limitation - INSTEAD OF DELETE/UPDATE triggers cannot be defined on a table that has a foreign key with a cascade on DELETE/UPDATE action defined but Insert Trigger can be defined.
I have one mysql table 'alfa' that will contain the primary key of another table 'beta' in one column. But if the entry in 'beta' can not be found I want to insert the value in 'beta' and use the new key in 'alfa'. Can I do this in one query somehow ?
I currently have:
INSERT INTO alfa SET c1=(SELECT id FROM beta WHERE name = 'john');
which works fine when 'john' exists in the table, but fails otherwise. So could I improve it to let the new name be inserted and selected if it is not already there ? id is auto_incremented.
I have tried to looking at IF but have not yet found out how to use IF outside the SELECT, is that possible ?
I know I can do it in several queries but I am talking with a remote database so could be nice to do it all at once.
For example the tables could have been created like this:
CREATE TABLE alfa (
c1 int,
PRIMARY KEY (c1)
)
CREATE TABLE beta (
id int auto_increment,
name varchar(255),
PRIMARY KEY (id)
)
so alfa.c1 should refer to the beta.id values.
In short I want to do:
insert the id for john from the beta table into c1 in alfa, if john does not exist in beta then insert john into beta and insert the new auto incremented id for john into c1 in alfa.
I'll have a go, but bear in mind that coming from a Microsoft SQL background, and I'm not familiar with the exact structure of your tables, so some of the the SQL is probably a bit ropey.
IF (SELECT COUNT(*) FROM beta WHERE name = 'John' > 0)
UPDATE alfa SET c1=(SELECT id FROM beta WHERE name = 'John')
ELSE
BEGIN
INSERT INTO beta (name) VALUES ('John')
INSERT INTO alfa (c1) VALUES (LAST_INSERT_ID())
END
Hope this is of some help.