Hello i have this problem:
I have 2 tables :
Create table Student(
Num int Auto_increment,
Name varchar(100),
Age int,
Gpa int default 2,
primary key(Num)
);
Create table Grades(
Num int,
Grade_BG int default 2,
Grade_Math int default 2,
Grade_SUBD int default 2,
Primary key (Num)
);
And i want to make a trigger to update the GPA with the three grades from the other table but i'm having hard time doing it.
Your trigger code :-
create trigger stud_marks after INSERT on Grades
for each row
update Student
set Gpa = (Grades.Grade_BG+Grades.Grade_Math+Grades.Grade_SUBD)/3;
The for each row means for each row inserted to grades so the grades. qualifier is unnecessary and should be replaced with NEW. 'Within the trigger body, the OLD and NEW keywords enable you to access columns in the rows affected by a trigger.' - https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html
Also the update needs to know which student to update so a where clause would be useful
so
create trigger stud_marks after INSERT on Grades
for each row
update Student
set Gpa = (new.Grade_BG+new.Grade_Math+new.Grade_SUBD)/3
where student.num = new.num;
Assuming num in grades actually relates to num in student. If not then you need to create a relationship.
You may also need to create UPDATE and DELETE triggers.
i would like that whenever i insert a row the newly generated id be used as a username and also get inserted in the user_name field. Any idea on how how i can achieve this will be much appretiated.
I have tried to run the below code on mysql workbench,and everything seem to work fine except for the insert statement.
create database if not exists mydatabase;
create table if not exists mydatabase.mytable
(
id int auto_increment not null,
user_name int not null,
pass_word varchar(100),
primary key(id)
);
insert into mydatabase.mytable(user_name,pass_word) values (select SCOPE_IDENTITY(),'mypass');
Not sure if your version of sql supports multiple auto_increment columns. However I'm thinking you could either create a trigger or insert the following every time you do an insert:
update my_table
set user_name = id
I have an old helpdesk ticketing system that I've been tasked with porting data out of and into our new ticketing system. Here's the query I'm running:
DROP TABLE IF EXISTS final_table;
CREATE TABLE final_table (
name varchar(40),
ticketID BIGINT,
ticket_id BIGINT,
subject varchar(255),
priority_id varchar(10),
status varchar(10),
updated DATE,
created DATE,
closed DATE,
response LONGTEXT
);
ALTER TABLE final_table ADD PRIMARY KEY(ticket_id);
INSERT INTO final_table
SELECT name, ticketID, ticket_id, subject, priority_id, status, updated, created, closed, response
FROM ost_ticket;
ALTER TABLE final_table ADD response LONGTEXT;
ALTER TABLE final_table ADD impact varchar(40);
ALTER TABLE final_table ADD category varchar(20);
ALTER TABLE final_table ADD queue varchar (20);
UPDATE final_table SET impact = "1 person can't work";
UPDATE final_table SET category = "Other";
UPDATE final_table SET queue = "Help Desk";
INSERT INTO final_table( response )
SELECT GROUP_CONCAT(ost_ticket_response.response SEPARATOR "\n\n") AS response
FROM ost_ticket_response
GROUP BY ost_ticket_response.ticket_id;
The old ticketing software has the PK listed multiple times in the ost_ticket_response table, hence the need for the GROUP_CONCAT call in the last four lines. Basically I'm trying to combine the entries that have the same ticket_id and then pull that into the temp table I'm creating. If I run the query as it stands now, it just populates the response column with null results. Any ideas?
Note: Apologies if this is a duplicate but I can't find a solution.
I have two databases (one dev and one live) which have exactly the same schema.
To make things easier to explain, assume I have a 'customer' table and a 'quote' table. Both tables have auto increment ids and the quote table has a 'customerid' column that serves as a foreign key to the customer table.
My problem is that I have some rows in my dev database that I want to copy to the live database. When I copy the customer rows I can easily get a new id, but how can i get the new id to be assigned to the 'child' quote table rows?
I know I can manually script out INSERTS to overcome the problem but is there an easier way to do this?
EDIT:
This is a simplified example, I have about 15 tables all of which form a hierarchy using auto-increments and foreign keys. There is considerably more data in the live database so the new ids will be bigger (e.g. dev.customer.id = 4, live.customer.id = 54)
Easiest way without changing any IDs.
Ensure that you are currently in the table where the record you want to copy is in (source db).
Run the following command:
INSERT INTO to_database.to_table
SELECT * FROM from_table WHERE some_id = 123;
No need to specify columns if there is no need to remap anything.
Hope that helps!
I eventually managed to do this (as per my comment) but in order to do so I had to write some code. In the end I created some dummy tables that kept track of the old id against new id so. When copying over records with FK constraints I just looked up the new id based on the old. A bit long winded but it worked.
This post is getting on a bit now so I've marked this as the answer. If anyone out there has better ideas/solutions that work I'll happily 'unmark' it as the accepted answer.
EDIT: As requested here is some pseudo-code that I hope explains how I did it.
I have the two related tables as follows:
CREATE TABLE tblCustomers (
Id int NOT NULL AUTO_INCREMENT,
Name varchar(50) DEFAULT NULL,
Address varchar(255) DEFAULT NULL,
PRIMARY KEY (Id)
)
ENGINE = MYISAM
ROW_FORMAT = fixed;
CREATE TABLE tblQuotes (
Id int NOT NULL AUTO_INCREMENT,
CustomerId int(11) DEFAULT NULL,
QuoteReference varchar(50) DEFAULT NULL,
PRIMARY KEY (Id)
)
ENGINE = MYISAM
ROW_FORMAT = fixed;
I create an extra table that I will use to track old ids against new ids
CREATE TABLE tblLookupId (
Id int NOT NULL AUTO_INCREMENT,
TableName varchar(50) DEFAULT NULL,
OldId int DEFAULT NULL,
NewId int DEFAULT NULL,
PRIMARY KEY (Id)
)
ENGINE = MYISAM
ROW_FORMAT = fixed;
The idea is that I copy the tblCustomer rows one at a time and track the ids as I go, like this:
// copy each customer row from dev to live and track each old and new id
//
foreach (customer in tblCustomers)
{
// track the old id
var oldid = customer.id; // e.g. 1
// insert the new record into the target database
INSERT newdb.tblCustomers (...) VALUES (...);
// get the new id
var newid = SELECT LAST_INSERT_ID() // e.g. 245
// insert the old id and the new id in the id lookup table
INSERT idlookup (TableName, OldId, NewId) VALUES ('tblCustomers', oldid, newid); // this maps 1->245 for tblCustomers
}
When I come to copy the table (tblQuote) with the foreign key I have to first lookup the new id based on the old.
// copy each quote row from dev to live and lookup the foreign key (customer) from the lookup table
//
foreach(quote in tblQuotes)
{
// get the old foreign key value
var oldcustomerid = quote.CustomerId; // e.g 1
// lookup the new value
var newcustomerid = SELECT newid FROM tblIdLookup WHERE TableName='tblCustomers' AND oldid=oldcustomerid; // returns 245
// insert the quote record
INSERT tblQuotes (CustomerId, ...) VALUES (newcustomerid, ...);
}
I've tried to keep this short and to the point (and language agnostic) so the technique can be seen. In my real scenario I had around 15 'cascading' tables so I had to track the new ids of every table not just tblCustomer
Use INSERT ... SELECT:
insert into your_table (c1, c2, ...)
select c1, c2, ...
from your_table
where c1, c2, ... are all the columns except id.
I am trying to create a database in SQL Server but it keeps throwing errors. Could you look at the script and see if I am messing it up somehow?
drop database if exists cptc;
create database cptc;
use cptc;
drop table if exists staff;
create table staff (
staffID int not null auto_increment,
fname varchar(25),
lname varchar(25),
title varchar(50),
phone varchar(10),
building varchar(10),
room varchar(10),
PRIMARY KEY(staffID),
FULLTEXT (fname,lname)
)ENGINE = MYISAM;
INSERT INTO staff VALUES ('','michael','herrera','doctor','2539703420','B14','122');
INSERT INTO staff VALUES ('','holly','herrera','teacher','2534667896','B35','116');
INSERT INTO staff VALUES ('','jesse','kirsch','professor','2534567890','B12','112');
INSERT INTO staff VALUES ('','mark','wahlberg','professor','5552345678','B01','112');
INSERT INTO staff VALUES ('','philip','spears','technician','2065672345','B12','123');
INSERT INTO staff VALUES ('','andrew','jackson','teacher','2061234567','B32','101');
INSERT INTO staff VALUES ('','annie','smith','mechanic','2533345609','B23','102');
INSERT INTO staff VALUES ('','alfred','hills','teacher','2535821513','B14','103');
INSERT INTO staff VALUES ('','bobby','jones','nurse','5559876056','B10','104');
INSERT INTO staff VALUES ('','tiffany','jones','janitor','2539981265','B02','108');
UPDATE: I think I was having Errors because it is MySQL and NOT SQL. Thanks everyone For Your (Really Quick) Answers!
This part is MYSQL not SQL Server ENGINE = MYISAM;
here is what the table would look like in SQL Server (sans the fulltext index, you first need to enable fulltext search in order to create a full text index))
create table staff (
staffID int not null identity,
fname varchar(25),
lname varchar(25),
title varchar(50),
phone varchar(10),
building varchar(10),
room varchar(10),
PRIMARY KEY(staffID)
)
The drop and create database will look like this
USE [master]
GO
IF EXISTS (SELECT name FROM sys.databases
WHERE name = N'cptc')
DROP DATABASE cptc
GO
CREATE DATABASE [cptc]
The drop table will look like this
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'staff') AND type in (N'U'))
DROP TABLE staff
GO
Finally, you need to ommit the column for the identity while inserting, example
INSERT INTO staff VALUES ('michael','herrera','doctor','2539703420','B14','122');
If you don't ommit the column, you will get the following error
Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'staff' can only be specified when a column list is used and IDENTITY_INSERT is ON.
auto_increment should be identity(1,1)
ENGINE = MYISAM; doesnt exist what do you expect with it?
FULLTEXT (fname, lname) is not correct. What do you want, implement full text serach?
The question was not clear. You were creating a table not database.
It would be helpful if you provide the actual error detail.
BTW, you shouldn't put any value for the autoincrement column which will be assigned by server automatically. I guess this was causing the issue.