Join inserted record with latest record target table - sql-server

i'm setting up a trigger that, in case of a new record being added to my source table, inserts a record into my target table with information based on the data in the first inserted record.
Since the new data in the target table are basically calculated fields based on the original latest record in the target table and the inserted record in the source table, i basically need a way to join the last record of my target table and my INSERTED table.
i've tried selecting the top row of my target table and join this with my INSERTED table, but so far it has not worked
CREATE TRIGGER dbo.NewData ON dbo.t_stats_lijn1 AFTER INSERT AS
IF Exists(select top 1 Categorie from INSERTED where Categorie = 'geen stop' order by p_timestamp desc)
begin
declare #joincause int = 0
insert into dbo.T_VALUE_LIJN1 ([Event ID]
,[p_timestamp]
,[Model]
,[Modelnaam]
,[running_time]
)
select
i.event_id,
i.p_timestamp
i.model
t.running_time + i.delta
from inserted i left join (select top 1 * from t_value_lijn1 order by p_timestamp) t on #joincause = 0
end
go

Related

SQL Server : AFTER INSERT trigger and INSERT INTO

I want to create a trigger that will fill up my sales history base after firing in the ORDER table.
I am creating a specific order in regular data base and after that this order automatically goes to sales_history database.
Below part works properly.
When I create a new order in regular database my sales_history database is growing with new ID_ORDERS, hooray! :)
ALTER TRIGGER [dbo].[InsertTrig]
ON [dbo].[ORDER]
AFTER INSERT
AS
IF EXISTS (SELECT *
FROM inserted i
WHERE i.ID_TYPE = 1) -- specific order type
BEGIN
INSERT INTO id.dbo.sales_history (id_order)
SELECT i.ID_ORDER FROM inserted i
END
The problem arises when I want join another table. The trigger stops working
ALTER TRIGGER [dbo].[InsertTrig]
ON [dbo].[ORDER]
AFTER INSERT
AS
IF EXISTS (SELECT *
FROM inserted i
WHERE i.ID_TYPE = 1) -- specific order type
BEGIN
INSERT INTO id.dbo.sales_history (id_order, id_item)
SELECT
inserted.ID_ORDER, ORDER_DETAILS.ID_ITEM
FROM
inserted
INNER JOIN
ORDER_DETAILS ON ORDER_DETAILS.ID_ORDER = inserted.ID_ORDER
END
I also tried this way, and still nothing :(
ALTER TRIGGER [dbo].[InsertTrig]
ON [dbo].[ORDER]
AFTER INSERT
AS
IF EXISTS (SELECT *
FROM inserted i
WHERE i.ID_TYPE = 1) -- specific order type
BEGIN
DECLARE #xyz AS numeric(18, 0)
SET #xyz = (SELECT inserted.ID_ORDER FROM inserted)
INSERT INTO id.dbo.sales_history (id_order, id_item)
SELECT
ORDER.ID_ORDER, ORDER_DETAILS.ID_ITEM
FROM
ORDER
INNER JOIN
ORDER_DETAILS ON ORDER_DETAILS.ID_ORDER = ORDER.ID_ORDER
WHERE
ORDER.ID_ORDER = #xyz
END
I want to create a trigger that will automatically fill up my sales history base after firing in ORDER table.
Your trigger is on the Order table, meaning SQL Server fires it after you insert records into the Order table. At which point, the relevant records in the Order_Details table couldn't have been inserted yet, because they have a foreign key to the Order table.
This is why an inner join between your inserted table and the Order_details table returns 0 rows.
If you want your sales_history from the order_details table, you have to populate it after you insert the records to the order_details table.
CREATE OR ALTER TRIGGER [dbo].[OrderDetails_AfterInsert]
ON [dbo].[ORDER_DETAILS]
AFTER INSERT
AS
INSERT INTO id.dbo.sales_history (id_order, id_item)
SELECT
inserted.ID_ORDER, inserted.ID_ITEM
FROM
inserted
INNER JOIN
[ORDER] ON [ORDER].ID_ORDER = inserted.ID_ORDER
WHERE [ORDER].ID_TYPE = 1 -- specific order type
As a side note: InsertTrig is bad name. Note the name of the trigger in my answer - it tells you exactly what this trigger is for, and on what table.

Creating Trigger to get data from one table to another and generating a timestamp

I am trying to track Inventory where data would be entered in an Excel sheet (SQL Spreads) and then updates the SQL table and then gather the sum of that data and put it onto another table that would then generate a timestamp to when it was changed/updated/inserted.
The Pictures with highlighted columns is where I want to have the data in.
(TotalBinLo --> Binlocation)
and then when Binlocation is populated (inserted/updated/deleted) generating a timestamp (MM/DD/YYYY HH:MM:SS)
This is what I've come up so far.
---This Trigger is working when pulling data from one table into another--
Create Trigger tr_BC_totalbinLoc
on bincount
After Update
AS
Begin
update OnHandInv
set OnHandInv.binlocation = bincount.totalbinlo
from bincount
inner join OnHandInv on bincount.partnumber = OnHandInv.PartNumber;
End
---Another Trigger (Works) but enters in date for all rows. (Don't want) (only need for one column.)
Create Trigger tr_totalbinLoc_OHI
On Onhandinv
After Update
AS
Update Onhandinv
set dateupdated = getutcdate()
where PartNumber in (select distinct PartNumber from onhandinv)
totalbinlo
ColNeedToPopu
You need to join the inserted table to OnHandInv. I have assumed that PartNumber is the primary key to join on.
You also need to remove deleted rows which exactly match, in other words rows where no change has actually been made.
CREATE OR ALTER TRIGGER tr_BC_totalbinLoc
ON bincount
AFTER UPDATE
AS
SET NOCOUNT ON;
IF NOT EXISTS (SELECT 1 FROM inserted)
RETURN;
UPDATE o
SET
binlocation = i.totalbinlo
dateupdated = getutcdate()
FROM (
SELECT partnumber, totalbinlo
FROM inserted i
EXCEPT
SELECT partnumber, totalbinlo
FROM deleted d
) i
INNER JOIN OnHandInv o ON i.partnumber = i.PartNumber;
GO

SQL Server 2008 - Ambiguous column name

I am trying to do a join between two tables but I am receiving this error
Ambiguous column name 'NurseWard'
Code:
select
#WardID = NurseWard
from
dbo.NurseTbl as o
inner join
inserted as i on o.NurseID = i.NurseID
This looks like the inserted table in a trigger. The inserted table has the same column names as the original table. From the linked article:
The inserted table stores copies of the affected rows during INSERT
and UPDATE statements. During an insert or update transaction, new
rows are added to both the inserted table and the trigger table. The
rows in the inserted table are copies of the new rows in the trigger
table.
The query has an alias on both the NurseTbl and inserted tables, and the inner join uses the aliases, but the select does not. You will need to add an alias to the NurseWard column in the select:
select #WardID = o.NurseWard -- or i.NurseWard depending on what you need
from dbo.NurseTbl as o
inner join inserted as i on
o.NurseID = i.NurseID

How to delete record w/out matching record from another table?

I have the following view (students w/o schyrsem) to show the list of record that don't have related record from SchYrSem table:
SELECT Students.IDNo, Students.LastName, Students.FirstName
FROM Students LEFT JOIN SchYrSem ON Students.[IDNo] = SchYrSem.[IDNo]
WHERE (((SchYrSem.IDNo) Is Null));
When I delete record it says:
view or function 'students w/o schyrsem' is not updatable because the modification affects multiple base tables.
Any idea how can I delete record from Students table w/o matching record in SchYrSem table?
DELETE s
FROM dbo.Students AS s
LEFT OUTER JOIN dbo.SchYrSem AS ss
ON ss.IDNo = s.IDNo
WHERE ss.IDNo IS NULL;
Or
DELETE s
FROM dbo.Students AS s
WHERE NOT EXISTS
(
SELECT 1
FROM dbo.SchYrSem
WHERE IDNo = s.IDNo
);
You shouldn't be trying to delete a row from the view, IMHO.

Trigger in SQL Server 2008 R2

I am trying to create a trigger in SQL Server 2008 R2. I have three tables and they have PK-FK -FK relationship.
I have a column in first table where column name is STATUS that column has value 'inactive' or 'active' and in second table I have column FKNEWLoanreviewfieldid which has multiple values C2,C4,C6 and in third table I have FKWarningtypeID has different value like 4,3,2,1.
I have to create a trigger so that if FKwarningtypeID is updated to value 4 then in first table (where I have status column) the column value of status will be modified to 'active'.
Can any body help me please.
You need something like this:
CREATE TRIGGER trg_UpdateYourColumn
FOR UPDATE ON dbo.YourThirdTableHere
AS
-- update the first table
UPDATE
dbo.YourFirstTableHere
SET
-- set [Status] to 'Active'
-- (I sure hope this isn't *REALLY* stored as a *STRING* value!)
[Status] = 'Active'
FROM
dbo.YourFirstTableHere t1
INNER JOIN
-- join first and second table on some common column
dbo.YourSecondTableHere t2 ON t1.XX = t2.XX
INNER JOIN
-- join second and third table on some common column
dbo.YourThirdTableHere t3 ON t2.YY = t3.YY
INNER JOIN
-- join third table with the "Inserted" pseudo table
Inserted i ON t3.ID = i.ID
INNER JOIN
-- join third table with the "Deleted" pseudo table
Deleted d ON t3.ID = d.ID
WHERE
i.FKwarningtypeID = 4 -- new value is 4
AND d.FKwarningtypeID <> 4 -- old value was *NOT* 4

Resources