SQL Trigger to add values of Two columns and store it in Third column - sql

i have a table with three columns say pqty,prqty and balqty.
what i want to do is, have to add values of pqty and prqty. and then it should be stored in balqty. while inserting or updating this table, each row must be affect.
i used this trigger, and it worked sometimes and most of times it wont. i dont know why.
CREATE TRIGGER tsl on stockledger
FOR update
AS declare #pqty int, #prqty int;
select #pqty=i.pqty from inserted i;
select #prqty=i.prqty from inserted i;
update Stockledger set balqty = (#pqty - #prqty)
PRINT 'AFTER Update trigger fired.'

I don't think this is a good use of a trigger. Instead, if you have the capacity, consider using a computed column (with PERSISTED to enhance performance):
ALTER TABLE StockLedger DROP COLUMN balqty;
ALTER TABLE StockLedger ADD COLUMN balqty AS pqty - prqty PERSISTED;

Related

update and concatenate columns in PostgreSQL

I want to update and concatenate 3 columns in a new a attribute I've already created in my table. However when I execute my code, it puts attributes that before had values in null.
My code example:
update saber2012_1
set estu_fecha_nacimiento = Concat(estu_nacimiento_dia,'/',estu_nacimiento_mes,'/',estu_nacimiento_anno);
In this picture all values that is in null before these had values.
when I make this update
ALTER TABLE saber2012_uno ADD COLUMN punt_c_naturales int;
update saber2012_uno set punt_c_naturales = round((PUNT_BIOLOGIA::numeric + PUNT_FISICA::numeric + PUNT_QUIMICA::numeric) / 3,0);
alter table saber2012_uno DROP COLUMN PUNT_BIOLOGIA;
alter table saber2012_uno DROP COLUMN PUNT_FISICA;
alter table saber2012_uno DROP COLUMN PUNT_QUIMICA;
all is well. but I do not know because previous update is incorrect.
Perhaps you want concat_ws():
update saber2012_1
set estu_fecha_nacimiento = concat_ws('/', estu_nacimiento_dia, estu_nacimiento_mes, estu_nacimiento_anno);
This will ignore any of the arguments that are NULL.
However, your update will not change any other columns in the table. Perhaps the results are just coming back in a different order, when you query after the update.

MSSQL Trigger for update is working only once

I'm going to create a trigger for update. Purpose of this trigger is that If muadurum column is changed , take the old value of mua_tarih in table fkayitlar and insert to another table mua_tarihleri.
My code block like;
ALTER TRIGGER [dbo].[trgr_fkayit_update]
ON [dbo].[fkayitlar]
AFTER UPDATE
AS
DECLARE #mua_durum_once NVARCHAR(10)
DECLARE #mua_durum_sonra NVARCHAR(10)
DECLARE #mua_tarih_once DATE
DECLARE #mua_yapan_once NVARCHAR(25)
DECLARE #kisi_id INT
Take the old value;
SELECT
#kisi_id=kayitid,
#mua_durum_once=muayenedurum,
#mua_tarih_once=muayenetarih,
#mua_yapan_once=mua_yapan
FROM deleted
Take the new value;
SELECT #mua_durum_sonra=muayenedurum FROM inserted
Check if value is changed ; if changed, Insert #mua_tarih to table mua_tarihleri with #kisi_id and #mua_yapan_once
IF #mua_durum_once='OLDU'
AND #mua_durum_sonra='OLMADI'
AND #mua_tarih_once IS NOT NULL
BEGIN
INSERT INTO mua_tarihleri(kayitid,mua_tarihi,mua_yapan)
VALUES(#kisi_id,#mua_tarih_once,#mua_yapan_once)
END
My problem is When I update more than one row in table fkayitlar,Trigger is working, but I see only one inserted row in table mua_tarihleri (only working once). I need to see more than one.(should be working more than once) Are not Triggers working on more than one process? or How can I solve this my problem?
The trigger only occurs once when the table is updated, no matter how many rows are updated. Therefore, you have to write your trigger body to operate on a set of rows, not a single row as you have done.
Should be something like:
ALTER TRIGGER [dbo].[trgr_fkayit_update]
ON [dbo].[fkayitlar]
AFTER UPDATE
AS
INSERT INTO mua_tarihleri(kayitid,mua_tarihi,mua_yapan)
SELECT deleted.kayitid, deleted.muayenedurum, deleted.muayenetarih, deleted.mua_yapan
FROM deleted
JOIN inserted ON deleted.kayitid = inserted.kayitid
WHERE deleted.muayenedurum='OLDU'
AND inserted.muayenedurum='OLMADI'
AND muayenetarih IS NOT NULL

How to write a trigger to get before and after values in a single table

I have two tables transcriptTable and trancript_log.
I need to get before and after values in trancriptTable_log (OldValue,New,Value) when any update accrue on transcriptTable.
I have a trigger for before and after update but only one trigger at a time is executed.
Create trancriptTable_log table with required columns
create trigger below (one trigger is enough)
CREATE TRIGGER INSERTEDAndDELETEDTableExample
ON transcriptTable
FOR UPDATE
AS
BEGIN
--to get the old value (insert statement may vary depend on your need and table)
insert into trancriptTable_log (column_1) SELECT <your_column_name> FROM DELETED
--to get the new value
insert into trancriptTable_log values (column_2) SELECT <your_column_name> FROM INSERTED
END

Trigger to update table column after insert?

I need to update a column in table after any record is added in same table
Here is my sql code
CREATE TRIGGER [dbo].[EmployeeInsert]
ON [dbo].[APP_Employees]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #EmployeeID AS bigint
SELECT #EmployeeID = ID FROM inserted
UPDATE [dbo].[APP_Employees]
SET [EmployeeTotalNumberOfAnnualLeave] = [EmployeeBalanceTheInitialNumberOfDaysOfAnnualLeaveIn]
WHERE ID=#EmployeeID
END
GO
and showing error
Msg 2714, Level 16, State 2, Procedure EmployeeInsert, Line 17
There is already an object named 'EmployeeInsert' in the database.
The error you're getting is because you have that trigger already, in your database. So if you want to create it again, you need to first drop the existing trigger (or use ALTER TRIGGER instead of CREATE TRIGGER to modify the existing trigger).
BUT: 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??
SELECT #EmployeeID = 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 !
-- drop the existing trigger
DROP TRIGGER [dbo].[EmployeeInsert]
GO
-- create a new trigger
CREATE TRIGGER [dbo].[EmployeeInsert]
ON [dbo].[APP_Employees]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
-- update your table, using a set-based approach
-- from the "Inserted" pseudo table which CAN and WILL
-- contain multiple rows!
UPDATE [dbo].[APP_Employees]
SET [EmployeeTotalNumberOfAnnualLeave] = i.[EmployeeBalanceTheInitialNumberOfDaysOfAnnualLeaveIn]
FROM Inserted i
WHERE [dbo].[APP_Employees].ID = i.ID
END
GO

SQL Trigger to update row

I need a SQL trigger that would zero pad a cell whenever its inserted or updated. Was curious if its best practice to append two strings together like I'm doing in the update command. Is this be best way to do it?
CREATE TRIGGER PadColumnTenCharsInserted ON Table
AFTER INSERT
AS
DECLARE
#pad_characters VARCHAR(10),
#target_column NVARCHAR(255)
SET #pad_characters = '0000000000'
SET #target_column = 'IndexField1'
IF UPDATE(IndexField1)
BEGIN
UPDATE Table
SET IndexField1 = RIGHT(#pad_characters + IndexField1, 10)
END
GO
Your padding code looks fine.
Instead of updating every row in the table like this:
UPDATE Table
update just the row that triggered the trigger:
UPDATE updated
Also, you've still got some extraneous code -- everything involving #target_column. And it looks like you're not sure if this is an INSERT trigger or an UPDATE trigger. I see AFTER INSERT and IF UPDATE.
Two questions:
What are you doing with #target_column? You declare it and set it with a column name, but then you never use it. If you intend to use the variable in your subsequent SQL statements, you may need to wrap the statements in an EXECUTE() or use sp_executesql().
The syntax "UPDATE Table..." is OK for your update statement assuming that "Table" is the name of the table you are updating. What seems to be missing is a filter of some kind. Or did you really intend for that column to be updated for every row in the whole table?
One way to handle this would be to declare another variable and set it with the PK of the row that is updated, then use a where clause to limit the update to just that row. Something like this:
DECLARE #id int
SELECT #id = Record_ID FROM INSERTED
-- body of your trigger here
WHERE Record_ID = #id
I like your padding code. It looks good to me.