Inserting data into another field in another table with Trigger - sql

I have a trigger that inserts a record value into Table1 and also inserts the same value into Table 2. Table 1 and Table 2 have the same columns.
Now i want to insert the value that is in Table 2 into a third table called user fields table, the QNo value in table 2 must be inserted into the alphanumericCol value in Table 3.
(in terminology terms as follows: trigger after insert on table 1
fetches number from table two and derives next number, then inserts
new number into table 3 and updates table two with the new number (so
that the next time trigger fires it will have the latest number).
Here is my trigger that inserts the number into Table 1 and 2:
alter trigger insertQNO
on table1
after insert as
begin
update Table1
set QNo ='Q150' + CAST(inserted.Id AS VARCHAR(4)) + '/' + RIGHT(CONVERT(VARCHAR(10),GETDATE(),103),7)
from Table1
join inserted on inserted.Id = Table1.ID;
SET IDENTITY_INSERT dbo.table2 ON;
insert into Table2 (Id, Qno)
(select ID, Qno from table1 )
end;
go
The results are the same as per the below:
Now how do i put Qno value from table 2 into Alphanumeric value in user fields table? This is the last part of my trigger but i just cant get it

Related

SQL Server trigger validation to insert or update

I have to develop a trigger for multiple value update for the Change_Table that contains two columns Article_C (primary key) and Status_C. The trigger activates when the Status_C column is updated and it needs to either insert or update the Target_Tablewhich columns are Article_T (primary key) and Status_T.
The Status column for both tables is a NOT NULL int
For insert validation: insert all Change_Table values (Articles & Status) that do not exist into the Target_Table.
For update condition: if the articles exist in the Target_Table, pass the updated status value to that table.
Status values are 1 or 2.
My current implementation:
CREATE TRIGGER [dbo].[Article_Trigger]
ON [dbo].[Change_Table]
AFTER UPDATE
NOT FOR REPLICATION
AS
IF UPDATE (Status_C)
BEGIN
INSERT INTO Target_Table (Article_T, Status_T)
SELECT Article_C, Status_C
FROM Change_Table
WHERE NOT EXISTS (SELECT * FROM Target_Table
WHERE Change_Table.Article_C = Target_Table.Article_T
AND Change_Table.Status_C = Target_Table.Status_T)
END
This is a rough idea of the insert but it only works once when the Change_Table is first updated and the target table is empty. After that I get an error "Violation of PRIMARY KEY constraint" due to duplicate primary key after updating the status for a second time due to the insert condition.
Query that gave error after second execution:
update Change_Table set status_c = 1 where Article_C in (1000,1003)
How can I modify this query to implement the update status condition to this trigger?
I think you could use deleted or inserted tables. These 2 virtual tables are working nicely with trigger. In you example, you may not need deleted table as you are not logging the historical changes.
CREATE TRIGGER [dbo].[Article_Trigger]
ON [dbo].[Change_Table]
AFTER UPDATE
NOT FOR REPLICATION
AS
IF UPDATE (Status_C)
BEGIN
--insert if not exist
INSERT INTO Target_Table
SELECT A.Article_C, A.Status_C
FROM inserted as A --the updated records from the source table will exist in the inserted virtual table
LEFT JOIN Target_Table as B
ON B.Article_T = A.Article_C
WHERE B.Article_T IS NULL
--update if exist
UPDATE A
SET A.Status_T = B.Article_C
FROM Target_Table as A
INNER JOIN inserted as B --the updated records from the source table will exist in the inserted virtual table
ON B.Article_C = A.Article_T
END

Creating INSTEAD OF UPDATE trigger to update HasChanged field in 3 tables

I've created a transform view that updates the master table with values from two different tables.
When doing this update, I need to change the 'HasChanged' value in all the tables for the affected records.
Ex: One row in the master table is updated with road name from one table and city name from another. The rows in the 2 tables that contained the new road name and city name must have their HasChanged value updated to 0 (from 1), as well as the master table.
For this I need to create a trigger. So far this is what I have:
CREATE TRIGGER [Transform].[trItems_HasChanged] ON [Transform].[vItems_HasChanged]
INSTEAD OF UPDATE
AS
BEGIN
SET NOCOUNT ON
CREATE TABLE #inserted
(
Id BIGINT
)
CREATE TABLE #PostnummerBy
(
Postnr BIGINT
)
CREATE TABLE #Vejstykke
(
Id BIGINT
)
INSERT INTO #Inserted (Infohub_Id)
SELECT Id FROM inserted
CREATE NONCLUSTERED INDEX ixInserted_Infohub_Id ON #Inserted (Infohub_Id)
UPDATE
InfohubStaging.Perfion.tMirror_Items
SET
Infohub_HasChanged = 0
FROM
InfohubStaging.Perfion.tMirror_Items
JOIN #Inserted i ON i.Infohub_Id = InfohubStaging.Perfion.tMirror_Items.Infohub_Id
WHERE
Infohub_HasChanged = 1
UPDATE
InfohubStaging.Nav.tMirror_PimItem
SET
Infohub_HasChanged = 0
FROM
InfohubStaging.Nav.tMirror_PimItem
JOIN #Inserted i ON i.Infohub_Id = InfohubStaging.Nav.tMirror_PimItem.InfohubId
WHERE
Infohub_HasChanged = 1
UPDATE
InfohubStaging.Ax.tMirror_Items_LiveUpdates
SET
Infohub_HasChanged = 0
FROM
InfohubStaging.Ax.tMirror_Items_LiveUpdates
JOIN #Inserted i ON i.Infohub_Id = InfohubStaging.Ax.tMirror_Items_LiveUpdates.Infohub_Id
WHERE
Infohub_HasChanged = 1
END
I am unsure how to correctly go about this. I'm aware that 2 temp tables are created when doing an update trigger (the data before and after). Since the temp tables are non-indexable, I need to create an index for them. So I need to create 3 tables, one for each of the tables who need to have their HasChanged value updated.
My expected output from this has the HasChanged value updated in the Vejstykke, PostnummerBy and Master table.

SQL Trigger update another table

I am newbie to triggers... can anybody help me with a trigger?
I have Table:
Name | Number
I want to write a trigger when my table receives a query like
update MyTable
set Number = Number + 1
where Name = 'myname'
When this query is running, the trigger should update another table for example:
Update MyTable 2
set Column = 'something'
where Name = 'myname (above name)
Thank you very much !
You will need to write an UPDATE trigger on table 1, to update table 2 accordingly.
Be aware: triggers in SQL Server are not called once per row that gets updated - they're called once per statement, and the internal "pseudo" tables Inserted and Deleted will contain multiple rows, so you need to take that into account when writing your trigger.
In your case, I'd write something like:
-- UPDATE trigger on "dbo.Table1"
CREATE TRIGGER Table1Updated
ON dbo.table1 FOR UPDATE
AS
BEGIN
-- update table2, using the same rows as were updated in table1
UPDATE t2
SET t2.Column = 'something'
FROM dbo.Table2 t2
INNER JOIN Inserted i ON t2.ID = i.ID
END
GO
The trick is to use the Inserted pseudo table (which contains the new values after the UPDATE - it has the exact same structure as your table the trigger is written for - here dbo.Table1) in a set-based fashion - join that to your dbo.Table2 on some column that they have in common (an ID or something).
create a trigger on table 1 for update:
CREATE TRIGGER dbo.update_trigger
ON table1
AFTER UPDATE
AS
BEGIN
DECLARE #Name VARCHAR(50)
SELECT #Name=Name FROM INSERTED
Update MyTable 2
SET Column = 'something'
WHERE Name = #Name
END
GO
try this ;)

Unable to copy Some coloumns using Trigger

I have a two database tables,that database tables connect with 1:1 relationship.Using a trigger i need to copy some coloumns data to Log table.(When New Insert or Update Happens)
Error (1) Invalid column name 'ItemTbl_ItemId'.
(2) Invalid column name 'Price'
(3)Column name or number of supplied values does not match table definition.
First Table has
Table Name - ItemTbl
ItemId, ItemName, ItemPrice,Comments, Brand_BrandId
Second Table
Table Name - ItemLog
ItemLogId, ItemTbl_ItemId,ItemName,ItemPrice,ModifiedDate
My Trigger
CREATE TRIGGER [dbo].[ItemHistoryTrigger]
ON [dbo].[ItemTbl]
FOR INSERT,UPDATE
AS
BEGIN
IF EXISTS(SELECT ItemId,ItemName,ItemPrice FROM INSERTED)
BEGIN
INSERT INTO [dbo].[ItemLog]
SELECT ItemTbl_ItemId,ItemName,ItemPrice FROM INSERTED;
END
END
I Just wanted to copy ItemName & ItemPrice from the first table to second table using trigger.
You have no column named ItemTbl_ItemId in the table you are creating the trigger (ItemTbl). Try this:
CREATE TRIGGER [dbo].[ItemHistoryTrigger]
ON [dbo].[ItemTbl]
FOR INSERT,UPDATE
AS
BEGIN
IF EXISTS(SELECT ItemId,ItemName,ItemPrice FROM INSERTED)
BEGIN
INSERT INTO [dbo].[ItemLog](ItemTbl_ItemId,ItemName,ItemPrice)
SELECT ItemId,ItemName,ItemPrice FROM INSERTED;
END
END
And this assumes that the ItemLog's columns ItemLogId and ModifiedDate are auto_incremented and have a default value respectively.

Get SCOPE_IDENTITY value when inserting bulk records for SQL TableType

I have following table structure, for convenience purpose I am only marking individual columns
Table_A (Id, Name, Desc)
Table_1 (Id this is identity column, Name....)
Table_2 (Id this is identity column, Table_A_Id, Table_1_Id)
The relationship between Table_1 and Table_2 is 1...*
Now I have created a table type for Table_A called TType_Table_A (which only contains Id as column and from my C# app I send multiple records). I have achieved this bulk insert functionality as desired.
What I need is when I insert records into Table_2 from TType_Table_A say with below statements, I would like to capture the Id of Table_2 for each record inserted
declare #count int = (select count(*) from #TType_Table_A); --a variable declared for TType_Table_A
if(#count > 0)
begin
insert into Table_2(Table_A_Id,Table_1_Id)
SELECT #SomeValue, #SomeValueAsParameter FROM #TType_Table_A;
end;
Now say if 2 records are inserted, I would like to capture the Id for each of these 2 records.
Any input/help is appreciated
This is what I know how it can be achieved, but I want to reduce DB calls from my app or user cursor in stored procedure
Insert record in Table_1 and return back the Id Loop.....through records and insert record in Table_2 and return back the Id
OR
Use cursor in stored procedure when inserting/selecting from TableType
I assume this is Sql Server? Then you can make use of the OUTPUT clause, like so:
declare #NewId table (MyNewId INT)
insert into Table_2(Table_A_Id,Table_1_Id)
output INSERTED.MyNewId INTO #TempTable(MyNewID)
SELECT SomeValue, SomeValueAsParameter FROM #TType_Table_A;
SELECT * FROM #NewId