Update and Insert Trigger - sql

I have four tables which constantly truncate then inserts and updates data every five minutes from another system into SQL Server. So I need to create an update and insert trigger to update another in SQL Server using if exists or merge.
Select
[Barcode]
,[TradingPartnerOrderNo]
,[ProductNo]
,[BarcodeCreatedDateTime]
,[BarcodeScheduledDateTime]
,[CancelledIndicator]
,[CancelledDateTime]
,[SiteIndicator]
,[InterfaceTimeStamp]
,[OperationDate]
,[Operation]
from [dbo].[BookingView]

For me it is not very clear your demande but here is a trigger example :
CREATE TRIGGER [dbo].[up_update_mytable]
ON [dbo].[MyTable] FOR UPDATE
AS
DECLARE #ID VARCHAR(50)
SELECT #ID = ID FROM INSERTED --Use INSERTED keyword for insert and update triggers to get informations of the inserted or updated record.
UPDATE MyOtherTable SET
Column1 = 'test value',
Column2 = 'test value 2'
WHERE OtherTableID = #ID

If you are using SQL Server 2008+, then you can use MERGE to do that. Something like this:
MERGE INTO table2 AS TGT
USING
(
Select
[Barcode]
,[TradingPartnerOrderNo]
,[ProductNo]
,[BarcodeCreatedDateTime]
,[BarcodeScheduledDateTime]
,[CancelledIndicator]
,[CancelledDateTime]
,[SiteIndicator]
,[InterfaceTimeStamp]
,[OperationDate]
,[Operation]
FROM [dbo].[BookingView]
) AS SRC ON SRC.Barcode = TGT.BarCode AND
WHEN NOT MATCHED THEN
INSERT (Barcode, TradingPartnerOrderNo, ...)
VALUES (SRC.Barcode, SRC.TradingPartnerOrderNo, ...);

Related

SQL - If not exists

I have a table in DB where some records exist.
When I add a new record I need to check by column "Name" if the record exists in DB. If such a record does not exist - then add it, if exists - then update. I'm trying like this:
USE [TestDB]
GO
DECLARE #daily nvarchar = 'DailySummaryEmailProcessor'
IF NOT EXISTS ( SELECT *
FROM [dbo].Crons
WHERE name = #daily)
BEGIN
INSERT INTO [dbo].Crons (CronJobID, Name, Description)
VALUES()
END
ELSE
BEGIN
UPDATE [dbo].Crons
SET
WHERE
END
MERGE should fit your requirements MERGE (Transact-SQL):
MERGE Crons AS target
USING (SELECT #Name) AS source (Name)
ON (target.Name = source.Name)
WHEN MATCHED THEN
UPDATE SET target.Name = source.Name
WHEN NOT MATCHED
INSERT INTO Crons (Name) VALUES (source.Name)
OUTPUT $action, deleted.Name, inserted.Name
the issue is you never declare the size of the variable #dialy
try this and see what do you get
DECLARE #daily nvarchar = 'DailySummaryEmailProcessor'
SELECT #daily
Looks like you need to do INSERT .. UPDATE.. check out MERGE statement
https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-2017
EDIT:
Oh.. you have MySQL there in the tag. My answer is specifically on SQL Server.

SQL Insert ,Update using Merge Store Procedure

I need to do a bulk Insert and/or Update for a target table in a SQL database. I have already tried the Merge stored procedure. In the target table I have a composite key.
I need to generate a pattern for first field (of the key) while inserting. I have tried a user-defined function that returns a pattern key which is unique for each of the rows.
My question is, how do I incorporate this function into a query that would auto-generate the key and insert the respective fields for each record?
TargetTable is my destination table in database and it has two columns - Key1(Bigint),Key2(int). Once again, this is a composite key.
Note: I only want to generate the key for the first field/column.
Here's my stored procedure:
Merge Targettable as T
Using SourceTable as s
ON s.Key1 = T.Key1 and
s.Key2=T.Key2
WHEN MATCHED THEN UPDATE
SET T.UserName = S.UserName
WHEN NOT MATCHED THEN
INSERT (Key1, Key2, UserName)
VALUES (dbo.UserDefiendFunction(#parama1),Key2,userName)
UserDefinedFunction returns the pattern i want.
Here's my User Defined Function:
Create function [dbo].[UserDefinedFunction] (
#Param1 int)
returns BIGINT
AS Begin
DECLARE #ResultVar BIGINT
SET #ResultVar=CONVERT(BIGINT, (SELECT Cast(#Param1 AS VARCHAR(10))
+ '' + Format((SELECT Count(userName)+1 FROM [dbo].[TableName]), '0')) )
RETURN #ResultVar
END
Please help me out with this. Thanks in advance.
IF EXISTS (SELECT * FROM Table1 join table 2 on Column1='SomeValue')
UPDATE Table1 SET (...) WHERE Column1='SomeValue'
ELSE
insert into ods..Table1 (Columname)
select [DatabaseName].[dbo].[UserDefinedFunction] (#paramater) as ColumnName

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 ;)

After insert not working

all id columns has auto_increment
In my trigger:
ALTER trigger [dbo].[mytrig]
on [dbo].[requests]
after INSERT, UPDATE
as
begin
declare #MyId1 int
set #MyId1 = (select Id from inserted)
declare #MyId2 int
declare #MyId3 int
if (select column1 from inserted) = 1
begin
insert into [dbo].[contracts] select column1,column2,column3 .... from inserted
set #MyId2 = SCOPE_IDENTITY()
insert into [dbo].[History] select column1,column2,column3 .... from inserted
set #MyId3 = SCOPE_IDENTITY()
insert into [dbo].[contracts_depts](Id_Contract ,column5) select #MyId2,column6 from request_depts where Id_request=#MyId1
insert into [dbo].[History_depts] (Id_InHistory,column5) select #MyId3,column6 from request_depts where Id_request=#MyId1
end
end
#MyId1 returns value only after update but not after insert. Do I have to use scope_identity() or something ?
Your main issue is: you're assuming the triggers is called once per row - that is NOT the case!
The trigger is called once per statement, and if your statement affects multiple rows, the Inserted pseudo table will contain multiple rows - so your statement here
set #MyId1 = (select Id from inserted)
really isn't going to work - it will select one arbitrary row (out of however many there are).
You'll need to rewrite your trigger to take this fact into account! Assume that Inserted contains 100 rows - how do you want to deal with that? What are you trying to achieve? Triggers don't return values - they will record into an audit table, or update other rows, or something like that ....

Updating a Table after some values are inserted into it in SQL Server 2008

I am trying to write a stored procedure in SQL Server 2008 which updates a table after some values are inserted into the table.
My stored procedure takes the values from a DMV and stores them in a table. In the same procedure after insert query, I have written an update query for the same table.
Insert results are populated fine, but the results of updates are getting lost.
But when I try to do only inserts in the stored procedure and I execute the update query manually everything is fine.
Why it is happening like this?
there should not be a problem in this.
below code working as expected.
create procedure dbo.test
as
begin
create table #temp (
name varchar(100) ,
id int
)
insert #temp
select name ,
id
from master..sysobjects
update #temp
set name='ALL Same'
from #temp
select * from #temp
drop table #temp
end
go
Best approach is to use Trigger, sample of AFTER UPDATE trigger is below:
ALTER TRIGGER [dbo].[tr_MyTriggerName]
ON [dbo].[MyTableName] AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
--if MyColumnName is updated the do..
IF UPDATE (MyColumnName)
BEGIN
UPDATE MyTableName
SET AnotherColumnInMyTable = someValue
FROM MyTableName
INNER JOIN Inserted
ON MyTableName.PrimaryKeyColumn = Inserted.PrimaryKeyColumn
END
END