Insert multiple rows into a table with a trigger on insert into another table - sql

I am attempting to create a T-SQL trigger that will essentially insert x number of rows into a third table based upon the data being inserted into the original table and data contained in a second table; however, I'm getting all sorts of errors in the select portions of the insert statement.
If I comment out this portion [qmgmt].[dbo].[skillColumns].[columnID] in (select columnID from [qmgmt].[dbo].[skillColumns]), IntelliSense gets rid of all the red lines.
Table designs:
Users table - contains user info
skillColumns table - list of all columns possible, filtered on the productGroupID of the user
Skills table - contains the data per user, one row for every columnID in skillColumns
CREATE TRIGGER tr_Users_INSERT
ON [qmgmt].[dbo].[Users]
AFTER INSERT
AS
BEGIN
INSERT into [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID])
Select [iTable].[userID],
[iTable].[displayName],
[cID] in (select [columnID] as [cID] from [qmgmt].[dbo].[skillColumns])
From inserted as [iTable] inner join
[qmgmt].[dbo].[skillColumns] on
[iTable].[productGroupID] = [qmgmt].[dbo].[skillColumns].[groupID]
END
GO
Is what I'm looking to accomplish even possible with a trigger? Can multiple rows be inserted into a table with the in keyword?
UPDATE:
After using the answer provided by J0e3gan, I was able to create a trigger in the opposite direction:
CREATE TRIGGER tr_skillColumns_INSERT_Users
ON [qmgmt].[dbo].[skillColumns]
AFTER INSERT
AS
BEGIN
INTO [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID])
Select [qmgmt].[dbo].[Users].[userID],
[qmgmt].[dbo].[Users].[displayName],
[iTable].[columnID]
From inserted as [iTable] inner Join
[qmgmt].[dbo].[Users] on
[iTable].[groupID] = [qmgmt].[dbo].[Users].[productGroupID]
Where
[qmgmt].[dbo].[Users].[userID] in (select [userID] from [qmgmt].[dbo].[Users])
END
GO

Yes, this can be done with an AFTER trigger.
The column list is not the correct place for the IN criterion that you are trying to use, which is why it is underlined in red.
Try adding the IN criterion to the JOIN criteria instead:
CREATE TRIGGER tr_Users_INSERT
ON [qmgmt].[dbo].[Users]
AFTER INSERT
AS
BEGIN
INSERT into [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID])
Select [iTable].[userID],
[iTable].[displayName],
[qmgmt].[dbo].[skillColumns].[columnID]
From inserted as [iTable] inner join
[qmgmt].[dbo].[skillColumns] on
[iTable].[productGroupID] = [qmgmt].[dbo].[skillColumns].[groupID] and
[qmgmt].[dbo].[skillColumns].[columnID] in (select columnID from [qmgmt].[dbo].[skillColumns])
END
GO
Alternatively add it to a WHERE clause:
CREATE TRIGGER tr_Users_INSERT
ON [qmgmt].[dbo].[Users]
AFTER INSERT
AS
BEGIN
INSERT into [qmgmt].[dbo].[Skills]([userID], [displayName], [columnID])
Select [iTable].[userID],
[iTable].[displayName],
[qmgmt].[dbo].[skillColumns].[columnID]
From inserted as [iTable] inner join
[qmgmt].[dbo].[skillColumns] on
[iTable].[productGroupID] = [qmgmt].[dbo].[skillColumns].[groupID]
Where
[qmgmt].[dbo].[skillColumns].[columnID] in (select columnID from [qmgmt].[dbo].[skillColumns])
END
GO

Related

Insert trigger doesnt do what i want it to do

i made a trigger which should avoid inserting a record in the rental 'uitlening' table if the person has an overdue payment (Boete). Unfortunately it doesnt work and i cant find the reason why. 'Boete' is an attribute of another table than rental. Can someone help me?
CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [dbo].[Uitlening]
FOR INSERT
AS
BEGIN
DECLARE #Boete decimal(10, 2);
SET #Boete = (SELECT Boete FROM Lid WHERE LidNr = (SELECT LidNr FROM inserted));
IF #Boete = 0
BEGIN
INSERT INTO Uitlening
SELECT *
FROM inserted;
END;
END;
It sounds like what you actually need is a cross-table constraint.
You can either do this by throwing an error in the trigger:
CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [Rental]
AFTER INSERT
AS
SET NOCOUNT ON;
IF EXISTS (SELECT 1
FROM inserted i
INNER JOIN dbo.Person p ON i.[personID] = p.[personID]
WHERE p.[PaymentDue] <= 0
)
THROW 50001, 'PaymentDue is less than 0', 1;
A better solution is to utilize a trick with an indexed view. This is based on an article by spaghettidba.
We first create a dummy table of two rows
CREATE TABLE dbo.DummyTwoRows (dummy bit not null);
INSERT DummyTwoRows (dummy) VALUES(0),(1);
Then we create the following view:
CREATE VIEW dbo.vwPaymentLessThanZero
WITH SCHEMBINDING -- needs schema-binding
AS
SELECT 1 AS DummyOne
FROM dbo.Rental r
JOIN dbo.Person p ON p.personID = r.personID
CROSS JOIN dbo.DummyTwoRows dtr
WHERE p.PaymentDue <= 0;
This view should in theory always have no rows in it. To enforce that, we create an index on it:
CREATE UNIQUE CLUSTERED INDEX CX_vwPaymentLessThanZero
ON dbo.vwPaymentLessThanZero (DummyOne);
Now if you try to add a row that qualifies for the view, it will fail with a unique violation, because the cross-join is doubling up the rows.
Note that in practice the view index takes up no space because there are never any rows in it.
Assuming you just want to insert records into [Rental] of those users, who have [PaymentDue] <= 0. As you mentioned in your last comment:
no record in rental can be inserted if the person has a PaymentDue
thats greater than zero
And other records should be silently discarded as you didn't give a clear answer to #Larnu's question:
should that row be silently discarded, or should an error be thrown?
If above assumptions are true, your trigger would look like:
CREATE TRIGGER [dbo].[Trigger_uitlening]
ON [Rental]
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO [Rental] ( [DATE], [personID], [productID])
SELECT i.[DATE], i.[personID], i.[productID]
FROM INSERTED i
INNER JOIN Person p ON i.[personID] = p.[personID]
WHERE p.[PaymentDue] <= 0
END;
Attention! When you create a trigger by FOR INSERT or AFTER INSERT then don't write insert into table select * from inserted, because DB will insert data automatically, you can do only ROLLBACK this process. But, when creating a trigger by INSTEAD OF INSERT then you must write insert into table select * from inserted, else inserting not be doing.

How to create trigger to check if table changed

I'm beginner and i trying to create trigger to check if table changed then i track the changed and insert it into another table
i created table called history and this is my code
create table history
(
ProjectNo INT ,
UserName NVARCHAR(50),
ModifiedDate date,
Budget_Old int,
Budget_New int,
)
and created this trigger
CREATE TRIGGER t1 on history
on project AFTER UPDATE
AS BEGIN
IF UPDATE(Project.Pnumber,Project.Budget)
INSERT INTO dbo.history (ProjectNo , Username,ModifiedDate,Budget_Old,Budget_New)
SELECT
d.ProjectNo, suser_name() ,GETDATE(),d.Budget,i.budget
FROM
Deleted d , inserted i
where d.projectno = i.projectno
END
i think my if statment is wrong but what i should do to make my query run right
to insert this values in history table ? plz help me and sorry for bad English
Triggers have access to two logical tables that have an identical structure to the table they are defined on which us Project as I assume.
INSERTED, which is the new data to go into the table
DELETED, which is the old data the is in the table
So You can get the old values in this way:
CREATE TRIGGER t1
ON dbo.Project AFTER UPDATE
AS
INSERT INTO dbo.history (ProjectNo , Username)
SELECT d.ProjectNo , d.Username
FROM DELETED d
If you need to just have one record for specific project in the table history, then you would use inner join based on the projectNo and update the history table accordingly.
ITS WORKS BUDDY ENJOY!!!!!!!!!!!
CREATE TRIGGER tRIGGERNAME1
BEFORE UPDATE on history
FOR EACH ROW
BEGIN
INSERT INTO dbo.history (ProjectNo ,Budget_Old,Budget_New)
VALUES(:OLD.ProjectNo,:OLD.Budget_Old,:NEW.Budget_New);
END;

How to get a inserted id in other table from inside a trigger?

I have 3 tables tbl_Users, tbl_Protocol and tbl_ProtocolDetails and inside of my trigger on Users, I have to inserted into Protocol and then insert into ProtocolDetails, but I don't know how work the inserted scope.
Something like that:
CREATE TRIGGER tg_Users ON tbl_Users
AFTER INSERT, UPDATE AS
BEGIN
DECLARE #UserId = Int
DECLARE #ProtocolId = Int
DECLARE #UserDetail = NVARCHAR(255)
SELECT
#UserId = user_id,
#UserDetail = user_detail + '#' + user_explanation
FROM INSERTED
INSERT INTO tbl_Protocol (user_id, inserted_date)
VALUES (#UserId, GetDate())
-- Return Inserted Id from tbl_Protocol into #ProtocolDetail then
INSERT INTO tbl_ProtocolDetails (protocol_id, protocol_details)
VALUES (#ProtocolId, #UserDetail)
END
Your trigger has a MAJOR flaw in that you seems to expect to always have just a single row in the Inserted table - that is not the case, since the trigger will be called once per statement (not once for each row), so if you insert 20 rows at once, the trigger is called only once, and the Inserted pseudo table contains 20 rows.
Therefore, code like this:
Select #UserId = user_id,
#UserDetail = user_detail + '#' + user_explanation
From INSERTED;
will fail, since you'll retrieve only one (arbitrary) row from the Inserted table, and you'll ignore all other rows that might be in Inserted.
You need to take that into account when programming your trigger! You have to do this in a proper, set-based fashion - not row-by-agonizing-row stlye!
Try this code:
CREATE TRIGGER tg_Users ON tbl_Users
AFTER INSERT, UPDATE AS
BEGIN
-- declare an internal table variable to hold the inserted "ProtocolId" values
DECLARE #IdTable TABLE (UserId INT, ProtocolId INT);
-- insert into the "tbl_Protocol" table from the "Inserted" pseudo table
-- keep track of the inserted new ID values in the #IdTable
INSERT INTO tbl_Protocol (user_id, inserted_date)
OUTPUT Inserted.user_id, Inserted.ProtocolId INTO #IdTable(UserId, ProtocolId)
SELECT user_id, SYSDATETIME()
FROM Inserted;
-- insert into the "tbl_ProtocolDetails" table from both the #IdTable,
-- as well as the "Inserted" pseudo table, to get all the necessary values
INSERT INTO tbl_ProtocolDetails (protocol_id, protocol_details)
SELECT
t.ProtocolId,
i.user_detail + '#' + i.user_explanation
FROM
#IdTable t
INNER JOIN
Inserted i ON i.user_id = t.UserId
END
There is nothing in this trigger that would handle a multiple insert/update statement. You will need to either use one scenario that will handle multiple records or check how many records were effected with a IF ##ROWCOUNT = 1 else statement. In your example, I would just use something like
insert into tbl_Protocol(user_id, inserted_date)
select user_id, user_detail + '#' + user_explanation
From INSERTED;
As for your detail table, I see Marc corrected his answer to include the multiple lines and has a simple solution or you can create a second trigger on the tbl_Protocol. Another solution I have used in the past is a temp table for processing when I have very complicated triggers.

Creating a trigger to insert records from a table to another one. Triggered column of table 'A' is inserted as null in table 'B' [duplicate]

This question already has an answer here:
Create a trigger to insert records from a table to another one. Get inserted values in a trigger
(1 answer)
Closed 9 years ago.
I have two tables tbl_PurchaseDetails and tbl_ItemDetails. I need to insert some records into tbl_ItemDetails from tbl_PurchaseDetails, right after it is inserted in tbl_PurchaseDetails. tbl_PurchaseDetails has auto generated custom field PurchaseID.
Code for auto generation of PurchaseID is:-
*This trigger works perfectly*
CREATE FUNCTION CreatePurchaseID (#id INT)
RETURNSvarchar(10)
AS
BEGIN
RETURN 'P' + CONVERT(VARCHAR(10), #id)
END
CREATE TRIGGER trigger_PurchaseID ON tbl_PurchaseDetails
FOR INSERT AS
UPDATE
tbl_PurchaseDetails
SET
tbl_PurchaseDetails.PurchaseID = dbo.CreatePurchaseID(tbl_PurchaseDetails.ID)
FROM
tbl_PurchaseDetails
INNER JOIN
INSERTED on tbl_PurchaseDetails.ID= INSERTED.ID
I have written the following code for trigger to insert into tbl_ItemDetails:-
CREATE TRIGGER trigger_UpdateItemDetails ON tbl_PurchaseDetails
FOR INSERT AS
DECLARE #PurchaseID VARCHAR(20)
DECLARE #Quantity INT
DECLARE #WarehouseID VARCHAR(20)
SELECT #PurchaseID=(PurchaseID) FROM INSERTED
SELECT #Quantity=(ItemQuantity) FROM INSERTED
SELECT #WarehouseID=(WarehouseID) FROM INSERTED
INSERT INTO
tbl_ItemDetails
(PurchaseID,Quantity,WarehouseID)
VALUES
(
#PurchaseID,#Quantity,#WarehouseID
)
**And now when i insert into tbl_PurchaseDetails the records are added to tbl_PurchaseDetails and tbl_ItemDetails successfully. The problem here is, the PurchaseID is inserted as null in tbl_ItemDetails. It is inserted as expected in tbl_PurchaseDetails though.
From my comments, here's what I'd have:
CREATE TABLE PurchaseDetails ( --Why have a tbl_ prefix on every table?
ID int IDENTITY(1,1) not null,
PurchaseID as 'P' + CONVERT(VARCHAR(10), ID),
--Other columns
)
I then wouldn't need your first trigger and function. I could then re-write the second trigger as:
CREATE TRIGGER trigger_UpdateItemDetails ON PurchaseDetails
FOR INSERT AS
INSERT INTO ItemDetails(PurchaseID,Quantity,WarehouseID)
SELECT PurchaseID,ItemQuantity,WarehouseID
FROM inserted
which deals with inserted potentially containing multiple rows.
Re: my comment in the first snippet about tbl_ prefixes - I'd argue that it's not just adding redundant information, it's adding potential for confusion. The only two types of objects that can appear, ambiguously, in the same position within a query are tables and views. Any other type of object (function, stored procedure, column, parameter, etc) can always be distinguished by syntax at the point of usage.
And, as much as possible, you shouldn't want or need to distinguish between tables and views. Being able to completely change a table, but then provide a view that has the same layout as the original table, and the same name, and then not having to change any other code is a great virtue in SQL. But it feels kind of silly when you have to name your view tbl_ABC because you were using tbl_ as a prefix for tables.

Insert into a temporary table and update another table in one SQL query (Oracle)

Here's what I'm trying to do:
1) Insert into a temp table some values from an original table
INSERT INTO temp_table SELECT id FROM original WHERE status='t'
2) Update the original table
UPDATE original SET valid='t' WHERE status='t'
3) Select based on a join between the two tables
SELECT * FROM original WHERE temp_table.id = original.id
Is there a way to combine steps 1 and 2?
You can combine the steps by doing the update in PL/SQL and using the RETURNING clause to get the updated ids into a PL/SQL table.
EDIT:
If you still need to do the final query, you can still use this method to insert into the temp_table; although depending on what that last query is for, there may be other ways of achieving what you want. To illustrate:
DECLARE
id_table_t IS TABLE OF original.id%TYPE INDEX BY PLS_INTEGER;
id_table id_table_t;
BEGIN
UPDATE original SET valid='t' WHERE status='t'
RETURNING id INTO id_table;
FORALL i IN 1..id_table.COUNT
INSERT INTO temp_table
VALUES (id_table(i));
END;
/
SELECT * FROM original WHERE temp_table.id = original.id;
No, DML statements can not be mixed.
There's a MERGE statement, but it's only for operations on a single table.
Maybe create a TRIGGER wich fires after inserting into a temp_table and updates the original
Create a cursor holding the values from insert and then loop through the cursor updating the table. No need to create temp table in the first place.
You can combine steps 1 and 2 using a MERGE statement and DML error logging. Select twice as many rows, update half of them, and force the other half to fail and then be inserted into an error log that you can use as your temporary table.
The solution below assumes that you have a primary key constraint on ID, but there are other ways you could force a failure.
Although I think this is pretty cool, I would recommend you not use it. It looks very weird, has some strange issues (the inserts into TEMP_TABLE are auto-committed), and is probably very slow.
--Create ORIGINAL table for testing.
--Primary key will be intentionally violated later.
create table original (id number, status varchar2(10), valid varchar2(10)
,primary key (id));
--Create TEMP_TABLE as error log. There will be some extra columns generated.
begin
dbms_errlog.create_error_log(dml_table_name => 'ORIGINAL'
,err_log_table_name => 'TEMP_TABLE');
end;
/
--Test data
insert into original values(1, 't', null);
insert into original values(2, 't', null);
insert into original values(3, 's', null);
commit;
--Update rows in ORIGINAL and also insert those updated rows to TEMP_TABLE.
merge into original original1
using
(
--Duplicate the rows. Only choose rows with the relevant status.
select id, status, valid, rownumber
from original
cross join
(select 1 rownumber from dual union all select 2 rownumber from dual)
where status = 't'
) original2
on (original1.id = original2.id and original2.rownumber = 1)
--Only math half the rows, those with rownumber = 1.
when matched then update set valid = 't'
--The other half will be inserted. Inserting ID causes a PK error and will
--insert the data into the error table, TEMP_TABLE.
when not matched then insert(original1.id, original1.status, original1.valid)
values(original2.id, original2.status, original2.valid)
log errors into temp_table reject limit 999999999;
--Expected: ORIGINAL rows 1 and 2 have VALID = 't'.
--TEMP_TABLE has the two original values for ID 1 and 2.
select * from original;
select * from temp_table;