How to insert a value in a trigger - sql

Im trying to insert a value when the condition occurs but it give me the error ambiguos column name
the code is:
create trigger B
on ALUNOS
after update, insert
as
begin
update ALUNOS
set média_final = 9 from inserted where média_final < 9
end

create trigger B
on ALUNOS
after update, insert
as
begin
update ALUNOS
set média_final = 9
from inserted i where i.média_final < 9
end
The ambiguous column is média_final which is in both tables. Specifying which table it came from is what you need to do.

try to follow this
update table set column = value where column = value
change value for the value that you want, you can add null or change null, don`t ever forget '' for string and lose it for numbers

Related

SQL Trigger - determine if a field has changed

I have this trigger
ALTER TRIGGER [dbo].[tInsertTaskFromOpportunityReassignment]
ON [dbo].[OpportunityBase]
FOR UPDATE
AS
BEGIN
IF UPDATE(owninguser)
BEGIN
-- do the task
END
END
I only want to do the task if owninguser has actually changed. How can I determine that?
Thanks
ALTER TRIGGER [dbo].[tInsertTaskFromOpportunityReassignment]
ON [dbo].[OpportunityBase]
FOR UPDATE
AS
BEGIN
DECLARE HasChanged int = 0;
SELECT #HasChanged = 1
FROM Inserted AS I
INNER JOIN Deleted AS D
ON I.PK = D.PK
AND IsNull(I.owninguser,'~') <> IsNull(D.owninguser,'~')
IF #HasChanged = 1
BEGIN
-- do the task
END
END
Compare the values of the field between Inserted and Deleted, joining the two tables on the primary key.
ALTER TRIGGER [dbo].[tInsertTaskFromOpportunityReassignment]
ON [dbo].[OpportunityBase]
FOR UPDATE
AS
BEGIN
/*
I will assume that your [dbo].[OpportunityBase] table has a PRIMARY KEY
or UNIQUE column that is immutable to join the inserted and deleted
tables. In this example, [OpportunityBaseId] is that column.
The SELECT query returns a set of all records that had the value of [owninguser]
changed. What you would do from that point is up to you.
*/
SELECT
i.[OpportunityBaseId], i.owninguser New_owninguser, d.owninguser Old_owninguser
FROM inserted i
JOIN deleted d
ON i.[OpportunityBaseId] = d.[OpportunityBaseId]
AND
(
--owninguser value was changed.
i.[owninguser] <> d.[owninguser] OR
--owninguser changed from non-NULL to NULL.
(i.[owninguser] IS NULL AND d.[owninguser] IS NOT NULL) OR
--owninguser changed from NULL to non-NULL.
(i.[owninguser] IS NOT NULL AND d.[owninguser] IS NULL)
)
END
GO
I like to use concat although it may potentially cause you problems with NULL and '':
CONCAT('', inserted.owninguser) <> CONCAT('', deleted.owninguser)

SQL Server After Update Trigger - Single Table - 2 Columns

I have a table (dbo.membersdatatable) that has multiple columns. I would like this trigger to update a column called "memberstatus" when "memberdesignation" is updated to a value of "10" from a value of "9".
-------SQL STATEMENT BELOW---------------
IF UPDATE([MemberDesignation])
--need to make it so it will recognize when memberdesignation = 10
UPDATE dbo.MembersDataTable
SET MemStatus = '0'
FROM dbo.MembersDataTable AS mdtbl
INNER JOIN inserted AS i ON i.StudentID = mdtbl.StudentID
Use triggers SPARINGLY. For example, my system has 138 tables, 550 stored procedures and only 28 triggers. I wish I had less.
But if you decide a trigger is required, it will look something like this:
CREATE TRIGGER [t_MemberDesignationSideEffect] ON [dbo].MembersDataTable
FOR UPDATE
AS
SET NOCOUNT ON
IF NOT ( UPDATE([MemberDesignation]) ) RETURN
-- REMINDER: All triggers can and will fire for a set of rows...not just one
UPDATE mdtbl
SET MemStatus = '0'
FROM inserted i
JOIN dbo.MembersDataTable mdtbl on i.StudentID = mdtbl.StudentID
JOIN deleted d on d.StudentID = mdtbl.StudentID
WHERE i.memberdesignation = '10'
and d.memberdesignation = '9'
GO
You are writing an update trigger on table. Here you can use deleted and inserted magic tables. In case of update trigger:
Deleted table contains the row as it was before the UPDATE statement.
Inserted table contains the row as it is after the UPDATE statement.
create trigger update_member_status
on membersdatatable
for update
as
begin
declare #old_designation int
declare #new_designation int
set #old_designation = (select memberdesignation from deleted)
set #new_designation = (select memberdesignation from inserted)
if (#old_designation = 9 and #new_designation = 10)
begin
update membersdatatable
set memstatus = '0'
from membersdatatable as mdtbl
inner join inserted as i on i.StudentID = mdtbl.StudentID
end
end
You are going to update member status of all rows with a
memberdesignation = 10
you can probably add conditions to this query in order to update only the ones you want by using a date field or another
Simply call this procedure after updating your table
CREATE PROCEDURE USP_MemberStatusRules()
AS
UPDATE dbo.MembersDataTable
SET MemStatus = '0'
WHERE memberdesignation = 10
AND .....
AND .....
GO

Populate extra database column depending on other column values

I have a database which collects data from an application. And now, I have to create another column that will be populated with predefined data depending on the values in other columns. So, no math, just to look up the values in two other columns and insert the data into the newly added column.
Example
id column1 column2 newColumn
1 15 3 100
So when column1 has 15, and column2 has 3, the newColumn should be auto-populated with 100. Again, the number 100 is predifned, not calcualted.
I know I can use triggers for new entries, but the database already has a large amount of data entered, so is there a way to auto populate the newColumn for data that is already tere?
EDIT --------------------------------
So I can use update to populate the column for the records that are already entered ?!
Can i make a trigger which will wait for both values and until both are entered it will return NULL?
You can create scalar function:
ALTER FUNCTION [dbo].[Test] ( #column1 INT, #column2 INT)
RETURNS INT
WITH SCHEMABINDING
AS
BEGIN
DECLARE #r INT
IF #column1 = 15 AND #column2 = 3
SET #r = 100
ELSE
SET #r = NULL
RETURN #r
END
And then add new computed column:
ALTER TABLE TableName ADD ColumnName AS dbo.Test(column1, column2) PERSISTED
Persisted means, that column is not calculated on the fly, but data is saved.
That's why you used WITH SCHEMABINDING. Without binding you can not make the column persisted.
You can also update your current data with simple update statement like in #Rhys Jones answer and add trigger on table like:
ALTER TRIGGER trTest ON TableName
AFTER INSERT, UPDATE
AS
BEGIN
IF UPDATE(column1) AND UPDATE(column2)
BEGIN
UPDATE TableName
SET NewColumn = CASE
WHEN column1 = 15 and column2 = 3 then 100
ELSE NULL
END
FROM Inserted i
JOIN TableName t ON t.id = i.id
END
END
You could just use a single UPDATE to update the missing values, then use the TRIGGER for new rows.
update MyTable set
newColumn = case
when column1 = 15 and column2 = 3 then 100
when ...
end
where
newColumn is null
However, note what #jarlh says above, there are usually better ways of doing this such as views or computed columns.

Trigger to delete prior duplicate records in the table

I need to write a trigger based on the following condition
Before inserting a record in the table, I need to compare the value of one column to the existing records, and if records found then I need to delete those records having same column value in the already existing records, and then need to insert that new record.
Please let me know how to achieve this.
Thanks
CREATE TRIGGER [dbo].[CustomInsert_Trigger] ON [dbo].[Realtimebookingcount]
INSTEAD OF INSERT AS
BEGIN
DECLARE #Flag INT
SELECT #Flag = Booking_NUM FROM inserted
IF (SELECT COUNT(1) FROM Realtimebookingcount
WHERE Booking_NUM = #Flag) > 0
BEGIN
DELETE FROM Realtimebookingcount
WHERE Realtimebookingcount.Booking_NUM = #Flag
END
INSERT INTO Realtimebookingcount
SELECT * FROM inserted
END

IF UPDATE() in SQL server trigger

If there's:
IF UPDATE (col1)
...in the SQL server trigger on a table, does it return true only if col1 has been changed or been updated?
I have a regular update query like
UPDATE table-name
SET col1 = 'x',
col2 = 'y'
WHERE id = 999
Now what my concern is if the "col1" was 'x' previously then again we updated it to 'x'
would IF UPDATE ("col1") trigger return True or not?
I am facing this problem as my save query is generic for all columns, but when I add this condition it returns True even if it's not changed...So I am concerned what to do in this case if I want to add condition like that?
It returns true if a column was updated. An update means that the query has SET the value of the column. Whether the previous value was the same as the new value is largely irelevant.
UPDATE table SET col = col
it's an update.
UPDATE table SET col = 99
when the col already had value 99 also it's an update.
Within the trigger, you have access to two internal tables that may help. The 'inserted' table includes the new version of each affected row, The 'deleted' table includes the original version of each row. You can compare the values in these tables to see if your field value was actually changed.
Here's a quick way to scan the rows to see if ANY column changed before deciding to run the contents of a trigger. This can be useful for example when you want to write a history record, but you don't want to do it if nothing really changed.
We use this all the time in ETL importing processes where we may re-import data but if nothing really changed in the source file we don't want to create a new history record.
CREATE TRIGGER [dbo].[TR_my_table_create_history]
ON [dbo].[my_table] FOR UPDATE AS
BEGIN
--
-- Insert the old data row if any column data changed
--
INSERT INTO [my_table_history]
SELECT d.*
FROM deleted d
INNER JOIN inserted i ON i.[id] = d.[id]
--
-- Use INTERSECT to see if anything REALLY changed
--
WHERE NOT EXISTS( SELECT i.* INTERSECT SELECT d.* )
END
Note that this particular trigger assumes that your source table (the one triggering the trigger) and the history table have identical column layouts.
What you do is check for different values in the inserted and deleted tables rather than use updated() (Don't forget to account for nulls). Or you could stop doing unneeded updates.
Trigger:
CREATE TRIGGER boo ON status2 FOR UPDATE AS
IF UPDATE (id)
BEGIN
SELECT 'DETECT';
END;
Usage:
UPDATE status2 SET name = 'K' WHERE name= 'T' --no action
UPDATE status2 SET name = 'T' ,id= 8 WHERE name= 'K' --detect
To shortcut the "No actual update" case, you need also check at the beginning whether your query affected any rows at all:
set nocount on; -- this must be the first statement!
if not exists (select 1 from inserted) and not exists (select 1 from deleted)
return;
SET NOCOUNT ON;
declare #countTemp int
select #countTemp = Count (*) from (
select City,PostCode,Street,CountryId,Address1 from Deleted
union
select City,PostCode,Street,CountryId,Address1 from Inserted
) tempTable
IF ( #countTemp > 1 )
Begin
-- Your Code goes Here
End
-- if any of these "City,PostCode,Street,CountryId,Address1" got updated then trigger
-- will work in " IF ( #countTemp > 1 ) " Code)
This worked for me
DECLARE #LongDescDirty bit = 0
Declare #old varchar(4000) = (SELECT LongDescription from deleted)
Declare #new varchar(4000) = (SELECT LongDescription from inserted)
if (#old <> #new)
BEGIN
SET #LongDescDirty = 1
END
Update table
Set LongDescUpdated = #LongDescUpdated
.....