Lookup data in one table and update another - sql-server-2008

I need a trigger that fires on update of a particular column in a table, and updates other columns using data from two other tables.
Table 1 is called STOCK_ITEMS
The columns concerned are all foreign keys
Column STOCKGROUP is FK for Table STOCK_GROUPS
Column STOCKGROUP2 is FK for Table STOCK_GROUP2S
Column X_STOCK_GROUP3 is FK for X_STOCK_GROUP3S
Table X_STOCK_GROUP3S contains the FKs of the other two stock group tables.
The idea is to make the first two columns dependent on the third, so that if the value of X_STOCK_GROUP3 changes, this trigger will set the values of STOCKGROUP and STOCKGROUP2 using the data from X_STOCK_GROUP3S
I tried this:
CREATE TRIGGER STOCKGROUP
ON [dbo].[STOCK_ITEMS]
FOR UPDATE
AS
IF UPDATE (X_STOCK_GROUP3)
set STOCKGROUP = STOCK_GROUPS.GROUPNO
PRINT 'AFTER UPDATE Trigger fired.'
GO
It does not work. It does not like my '=' sign. Or is there something else I'm missing (likely!!)
Any and all help appreciated.

Don' know if I understand what you want to do.
X_STOCK_GROUP3S contains some records like
(ID,STOCKGROUP,STOCKGROUP2)
(21,1000,300)
(22,2000,200)
(23,3000,100)
and STOCK_ITEMS contains records like
(ID,...,STOCKGROUP,STOCKGROUP2,X_STOCK_GROUP3)
If X_STOCK_GROUP3 of table STOCK_ITEMS is updated to 21 you want to set the values STOCKGROUP to 1000 and STOCKGROUP2 to 300.
Is this what you want to accomplish?
Then your code is missing some selection criteria.
I would try something like this
CREATE TRIGGER STOCKGROUP
ON [dbo].[STOCK_ITEMS]
FOR UPDATE
AS
SET NOCOUNT ON;
IF UPDATE (X_STOCK_GROUP3)
UPDATE STOCK_ITEMS SET STOCKGROUP = (
SELECT STOCKGROUP FROM X_STOCK_GROUP3S
WHERE STOCK_ITEMS.X_STOCK_GROUP3 = X_STOCK_GROUP3S.ID
),
STOCKGROUP2 = (
SELECT STOCKGROUP2 FROM X_STOCK_GROUP3S
WHERE STOCK_ITEMS.X_STOCK_GROUP3 = X_STOCK_GROUP3S.ID
)
WHERE ID IN (SELECT ID FROM deleted);
GO

OK, so here is the final, and successful, result:
Kudos credit: Sonny Dhaliwal - Support Consultant - Enprise Solutions. Thanks Sonny.
USE [MyDataBase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[X_SET_STOCK_GROUPS]
ON [dbo].[STOCK_ITEMS]
FOR UPDATE
AS
DECLARE #STOCKCODE VARCHAR(100),
#STOCKGROUP3 INTEGER,
#STOCKGROUP1 INTEGER,
#STOCKGROUP2 INTEGER
BEGIN
SELECT #STOCKCODE = STOCKCODE FROM inserted
SELECT #STOCKGROUP3 = X_STOCK_GROUP3 FROM inserted
SELECT #STOCKGROUP1 = (SELECT SECONDARY_GROUP FROM X_STOCK_GROUP3S
WHERE SEQNO = #STOCKGROUP3)
SELECT #STOCKGROUP2 = (SELECT PRIMARY_GROUP FROM X_STOCK_GROUP3S
WHERE SEQNO = #STOCKGROUP3)
BEGIN
UPDATE STOCK_ITEMS
SET STOCKGROUP = #STOCKGROUP1, STOCKGROUP2 = #STOCKGROUP2
WHERE STOCKCODE = #STOCKCODE
END
END
GO

Related

MySQL trigger - how to update specific row in another table

I have these two tables
**Table tb_data**
tb_id
timestamp
pagid
proid
status
(and many more)
**Table tb_units**
pag_id
pag_sn
user
latest_profile
latest_status
latest_feedback
latest_timestamp
Whenever a new row is created in tb_data, i would like some values updated in tb_units. In tb_units pag_id is unique and every number only exists once.
How do I trigger this, so the new values in tb_data are updated in tb_units? pagid equals pag_id and the corresponding values proid should update latest_profil, status should update latest_status, timestamp should update latest_timestamp
In the end I would like to end up with the latest pagid input to tb_data to be available in tb_units, since tb_data will contain multiple rows from the same pagid
I hvae tried several different aproaches, and have read a lot of examples, but I just don't get how these triggers work!
Latest example, that doesn't work:
CREATE TRIGGER update_units
AFTER INSERT ON tb_data
BEGIN
UPDATE tb_units
SET latest_profile = tb_data.9C,
latest_status = tb_data.91
WHERE pag_id = tb_data.86;
END
Not sure but something like this should work
CREATE TRIGGER update_units
AFTER INSERT ON tb_data
BEGIN
UPDATE tb_units
SET latest_profile = new.proid,
latest_status = new.status
WHERE pag_id = new.pagid;
END

Insert a record and also update existing records

hi there i was trying to right a Proc for a DataLoad when you want to insert records on a Table1 based on Table2
This is what i came of with
it has 2 condition
1) if the record does not exist create a new row of record
2) if the record already exist update the record based on keys
this is my proc need some help thanks
DECLARE #TableKey INT --(it is passed by the user proc param),
DECLARE #TableCount INT,
DECLARE #CLassKey INT,
SELECT #TableCount= COUNT(*) FROM Table1 WHERE Tablekey= #TableKey
INSERT INTO #CLassKey
SELECT Distinct c.PK_ClassKey FROM CLASS as c
INNER JOIN BOOK as B ON B.FK_ClassKey=C.PK_ClassKEy
IF ((SELECT COUNT(*) FROM #ClassKey) > 0 AND #TableCount= 0)--- this will check
BEGIN
Insert into NOTE
n.note
Select
c.note
FROM Class where c.FK_Note = n.PK_Note.
END
---- this will just insert for the first time..
How do i update it any idea as the records are only inserted for the first time put does not update using the same format thanks a lot
try this one
INSERT INTO table_name (id,col2,col3)
VALUES (value_id,value2,value3)
ON DUPLICATE KEY UPDATE
col2=value2,
col3=value3;

Set max value as default value

I'm trying to store the order of the products in a database, and I want every new product added to be at the last position. Basically, I want the "rank" field to be set to MAX + 1, and MAX should be the highest value between the entries having the same "type".
I tried to do with a trigger, but since MySQL won't let me do that since the trigger would be executed on the same table :
**#1442 - Can't update table 'products' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. **
Here is what my trigger was like :
CREATE TRIGGER `productInsert`
AFTER INSERT ON `products`
FOR EACH ROW
BEGIN
UPDATE products
SET rank = (SELECT MAX(rank)
from products
where type_id = NEW.type_id)
where id = NEW.id
Is there any other way to do that?
Thanks
You want a before insert trigger:
CREATE TRIGGER `productInsert`
BEFORE INSERT ON `products`
FOR EACH ROW
BEGIN
set NEW.rank = (select max(rank) + 1
from products p
where p.type_id = NEW.type_id
);
END

Using and UPDATE Trigger to Modify the Row Being Updated

I have an employee table (em) that contains, among other things, a floor Id (fl_id) and room Id (rm_id). In certain circumstances (when em_loc_cnt = 0) I want to set the em record's fl_id and rm_id to null. Below is my code so far.
I am not sure how to refer to the fl_id & rm_id in the commented line. Will I run into issues because this trigger is being called as a result of the em record being updated and I am updating that same record in the trigger?
Suggestions?
IF EXISTS (SELECT * FROM [sysobjects] WHERE [name] = 'em_upd_self_serv_t' AND [type] = 'TR')
BEGIN
DROP TRIGGER [dbo].[em_upd_self_serv_t]
END
GO
CREATE TRIGGER [dbo].[em_upd_self_serv_t]
ON [dbo].[em]
AFTER UPDATE
AS
BEGIN
DECLARE #em_id VARCHAR(35),
#em_loc_cnt INT;
SET #em_id = (SELECT em_id FROM inserted);
SET #em_loc_cnt = (SELECT COUNT(*) FROM emlocs WHERE em_id = #em_id);
IF (#em_loc_cnt = 0)
BEGIN
-- I want to set the fl_id and the rm_id to NULL
END
END;
Your fundamental flaw is that you seem to expect the trigger to be fired once per row - this is NOT the case in SQL Server. Instead, the trigger fires once per statement, and the pseudo table Inserted might contain multiple rows.
Given that that table might contain multiple rows - which one do you expect will be selected here??
SET #em_id = (SELECT em_id FROM inserted);
It's undefined - you might get the values from arbitrary rows in Inserted.
You need to rewrite your entire trigger with the knowledge the Inserted WILL contain multiple rows! You need to work with set-based operations - don't expect just a single row in Inserted !
You need to change your code to something like this:
IF EXISTS (SELECT * FROM sys.triggers WHERE [name] = 'em_upd_self_serv_t')
DROP TRIGGER [dbo].[em_upd_self_serv_t]
GO
CREATE TRIGGER [dbo].[em_upd_self_serv_t]
ON [dbo].[em]
AFTER UPDATE
AS
UPDATE dbo.em
SET fl_id = NULL, rm_id = NULL
FROM Inserted i
WHERE em_id = i.em_id
AND NOT EXISTS (SELECT * FROM dbo.emlocs WHERE em_id = i.em_id)

Update Table A with content from Table B

Im trying to make a trigger in mySQL that will update a colum with data from another table, when i do a insert.
I got table: rtsEP_groups
With: id, name
and table: rtsEP_users
with: id, groups (and alot of others)
And i want to update "groups" in rtsEP_users, with the "id" from rtsEP_groups where "name" is "Student", when there is a new insert in rtsEP_users.
I was working on this trigger, but not sure if its right, and how to finish it.
How to update the right colum.
CREATE TRIGGER defaultGroup
AFTER INSERT ON rtsEP_users
BEGIN
DECLARE _group_id INTEGER;
SELECT id INTO _group_id FROM rtsEP_groups WHERE name = "Student"
UPDATE rtsEP_users SET groups = _group_id WHERE
Use BEFORE INSERT instead of AFTER, so New is represent of inserted row that you can update.
Try this
CREATE TRIGGER defaultGroup BEFORE INSERT ON rtsEP_users
FOR EACH ROW
SET New.groups = (SELECT id FROM rtsEP_groups WHERE name = "Student");