create table tab(id int identity,task_id int,task_descp varchar(10),task_code varchar(10))
insert into tab values(7,'BUS','B')
insert into tab values(3,'CAR','C')
create table tab_detail( task_descp varchar(10),task_code varchar(10),color varchar(10))
create trigger tab_trigger on tab for insert as
declare #task_descp varchar(10)
declare #task_code varchar(10)
declare #task_id int
set #task_descp=i.task_descp from inserted i
set #task_code=i.task_code from inserted i
set #task_id=i.task_id from inserted i
if(#task_id=7)
insert into tab_detail values(#task_descp,#task_code,'BLUE')
if(#task_id=3)
insert into tab_detail values(#task_descp,#task_code,'GREEN')
go
I want to create a trigger for table tab where if I insert a record based on the task_id column a record has to be inserted into another table tab_detail.
When executing this I get this error:
Incorrect syntax near the keyword 'from'
Instead of:
set #task_descp=i.task_descp from inserted i
Try this:
select #task_descp=i.task_descp from inserted i
Or you could do this:
create trigger tab_trigger on tab for insert as
insert into tab_detail
select task_descp, task_code, case #task_id when 7 then 'BLUE' else 'GREEN' end
from inserted
where taskid in (7,3)
go
Change the SET to SELECT. Also, inserted is a recordset, not a single value. Fixing the code issue still might result in a run time issue!
This code should work fine for a recordset of information.
CREATE TRIGGER tab_trigger ON tab FOR INSERT AS
BEGIN
-- nothing to do?
IF (##rowcount = 0) RETURN;
-- do not count rows
SET NOCOUNT ON;
-- inserted data
INSERT INTO tab_detail
SELECT
i.task_descp,
i.task_code,
CASE i.taskcode
WHEN 7 THEN 'BLUE'
WHEN 3 THEN 'GREEN'
ELSE ''
END
FROM inserted i
WHERE i.task_code in (3, 7)
END
GO
Related
I'm trying to get the last identity from my table 'usergold' and insert it in a new table table with insert value. I used select "IDENT_CURRENT('UserGold') As userid", new value should be in userid.
But I'm getting an error when I put it in insert, I cannot create the trigger. Please check my code.
create trigger addrole
on UserGold
after Insert
as
Begin
select IDENT_CURRENT('UserGold') As userid
insert into AspNetUserRoles values(userid,'2c258e8d-c648-4b38-9b01-989d4dd525fe')
end
i tried
create trigger addrole
on UserGold
after Insert
as
Begin
declare
#userid nvarchar(50)
select #userid=userId from UserGold where userId=IDENT_CURRENT('UserGold')
insert into AspNetUserRoles(UserId,RoleId) values(#userid,'2c258e8d-c648-4b38-9b01-989d4dd525fe')
end
igot this error "Error converting data type nvarchar to numeric " from
select #userid=userId from UserGold where userId=IDENT_CURRENT('UserGold')
Your INSERT statement is not written correctly.
Try
INSERT INTO AspNetUserRoles ( [col_1_name], [col_2_name] )
VALUES (
( SELECT IDENT_CURRENT ( 'UserGold' ) ),
'2c258e8d-c648-4b38-9b01-989d4dd525fe'
);
Note: Replace the column holder names ( col_1_name, col_2_name ) with the actual column names being inserted to.
I have a view getting data from others views when data is inserted in this specific view as show bellow need to insert in table vendas ref(nvarchar(50)) and Estado(bool).
ALTER TRIGGER [dbo].[TGR_VENDAS]
ON [dbo].[VendasFinal]
INSTEAD OF INSERT
AS
BEGIN
DECLARE
#Ref nvarchar(50),
#EstadoString nvarchar(50)
SELECT #Ref = i.ref, #EstadoString = i.ESTADO
FROM inserted i
if(#EstadoString = 'Em Aberto')
BEGIN
INSERT INTO dbo.Vendas
(ref, Estado)
VALUES
(#Ref ,0);
END
ELSE
BEGIN
INSERT INTO dbo.Vendas
(ref, Estado)
VALUES
(#Ref ,1);
END
END
It's running on a MS Sql Server 11.0.
Thanks in advance.
You don't need a cursor here. You just need to use a case expression. Your posted trigger can be simplified to this. It handles any number of rows and the logic you have in the existing code.
ALTER TRIGGER [dbo].[TGR_VENDAS]
ON [dbo].[VendasFinal]
INSTEAD OF INSERT
AS
BEGIN
INSERT INTO dbo.Vendas
(
ref
, Estado
)
SELECT i.ref
, case when i.ESTADO = 'Em Aberto' then 0 else 1 end
from inserted i
I'm new to SQL Server, and I'm trying to build a simple update trigger that writes a row to a staging table whenever the column ceu_amount is updated from zero to any number greater than zero.
From using PRINT statements, I know that the variables are containing the correct values to execute the INSERT statement, but no rows are being inserted.
Can you help?
CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
--
-- Variable definitions
--
DECLARE #product_code_new as varchar(31)
DECLARE #product_code_old as varchar(31)
--
-- Check if the staging table needs to be updated.
--
SELECT #product_code_new = product_code FROM Inserted where ISNULL(ceu_amount,0) > 0;
SELECT #product_code_old = product_code FROM Deleted where ISNULL(ceu_amount,0) = 0;
IF #product_code_new IS NOT NULL
AND #product_code_old IS NOT NULL
INSERT INTO Product_Function_Staging VALUES (#product_code_new,CURRENT_TIMESTAMP);
END;
This part of code looks suspicious to me..
SELECT #product_code_new = product_code FROM Inserted where ISNULL(ceu_amount,0) > 0;
SELECT #product_code_old = product_code FROM Deleted where ISNULL(ceu_amount,0) = 0;
IF #product_code_new IS NOT NULL
AND #product_code_old IS NOT NULL
INSERT INTO Product_Function_Staging VALUES (#product_code_new,CURRENT_TIMESTAMP);
The above will work fine ,if there is only one row updated,what if there is more than one value..the product_code will default to last value
You can change the above part of code to below
Insert into Product_Function_Staging
select product_code ,CURRENT_TIMESTAMP from inserted where product_code is not null
You will get undetermined values for #product_code_new if there are more than one rows updated with ceu_amount>0; Similar for #product_code_old if more than one rows updated with ceu_amount NULL or equal 0.
Can you post some sample data?
I would not use variables like that in a trigger, since what causes the trigger could be an update to more than one row, at which point you would have multiple rows in your updated and deleted tables.
I think we can more safely and efficiently make this insert with one simple query, though I'm assuming you have a unique key to use:
CREATE TRIGGER [dbo].[TRG_Product_Function_Modified] ON [dbo].[Product_Function]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Product_Function_Staging
SELECT i.product_code, CURRENT_TIMESTAMP
FROM inserted i
JOIN deleted d ON i.product_code = d.product_code -- assuming product_code is unique
WHERE i.ceu_amount > 0 -- new value > 0
AND ISNULL(d.ceu_amount, 0) = 0; -- old value null or 0
END;
I'm not sure where you need to check for nulls in your data, so I've made a best guess in the where clause.
Try using this
CREATE TRIGGER [dbo].[Customer_UPDATE]
ON [dbo].[Customers]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #CustomerId INT
DECLARE #Action VARCHAR(50)
SELECT #CustomerId = INSERTED.CustomerId
FROM INSERTED
IF UPDATE(Name)
BEGIN
SET #Action = 'Updated Name'
END
IF UPDATE(Country)
BEGIN
SET #Action = 'Updated Country'
END
INSERT INTO CustomerLogs
VALUES(#CustomerId, #Action)
END
I want to make a trigger for one table that will be used before INSERT.
I want to check if two columns are NULL and if they are NULL raise an error otherwise INSERT the data.
So far I have this:
CREATE TRIGGER INS_TABLE_1
ON mytable
FOR INSERT
AS
BEGIN
IF (column1 IS NULL OR column2 IS NULL)
BEGIN
RAISERROR ('You are not allowed to Add These Data.', 10, 11)
END
ELSE
INSERT INTO mytable (column1,column2,column3)
END
Can you please help me?
Use instead trigger and inserted table like below and have a try.
CREATE TRIGGER INS_TABLE_1
ON mytable
INSTEAD OF INSERT
AS
BEGIN
DECLARE #fn varchar(50),#ln varchar(50)
SELECT #fn=column1 ,#ln=column12 from inserted
IF (#fn IS NULL OR #ln IS NULL)
BEGIN
RAISERROR ('You are not allowed to Add These Data.', 10, 11)
END
ELSE
INSERT INTO mytable (column1 ,column2) values (#fn,#ln)
END
The inserted table stores copies of the affected rows during INSERT and UPDATEstatements. Instead of trigger replaces the current INSERT by the trigger definition.
I am trying to write a trigger which would audit a table's every field - a row's old value and new value in a table. If any of the field has been modified, I need to save the fields old value and the new value along with field name in an audit table, as a new entry.
create trigger Trg_Institution_FieldAudit on Table1 AFTER UPDATE AS
DECLARE #OldName VARCHAR(30)
DECLARE #CurrentName VARCHAR(30)
DECLARE #OldId VARCHAR(30)
DECLARE #CurrentId VARCHAR(30)
DECLARE #modifiedBy VARCHAR(30)
If update(Name)
BEGIN
select #OldName = Name from deleted
select #CurrentName = Name from Inserted
select #OldId = ID from deleted
select #currentId = ID from Inserted
select #modifiedBy = modifiedBy from deleted
--INSERT statement for Name field alone
END;
This works fine for a small number of fields, but I have a lot of fields (more than 60), and I am not achieving the performance that is required, because of a lot of if conditions. Is there a better way of doing this? On top of this, there are concurrent updates that are happening to around 3 million records in this table, which makes a lot of things go wrong :(
EDIT: Only ONE row will get updated by an UPDATE statement
Oh my. Please avoid using a cursor whenever possible! You can easily use an insert statement with a select referencing the inserted and deleted tables. Below is a sample from one of my update triggers.
DECLARE #AuditTime DATETIME
SET #AuditTime = GetDate()
IF UPDATE([AccountManager])
INSERT INTO Audit.AuditHistory (AuditId, AuditDate, AuditTableName, EntityKey, AuditFieldName, OldValue, NewValue, FieldDisplayText, OldDisplayText, NewDisplayText, ModifiedBy)
SELECT NewId(),
#AuditTime,
'[tblOpportunity]',
cast(d.[GOTSID] AS varchar),
'[AccountManager]',
cast(d.[AccountManager] AS varchar(250)),
cast(i.[AccountManager] AS varchar(250)),
'Account Manager',
isnull(cast(d.[AccountManager] AS varchar(250)), ''),
isnull(cast(i.[AccountManager] AS varchar(250)), ''),
isnull(i.[ModifiedBy], '')
FROM deleted d
INNER JOIN inserted i ON d.GOTSID = i.GOTSID
WHERE d.[AccountManager] <> i.[AccountManager]
OR (d.[AccountManager] IS NOT NULL
AND i.AccountManager IS NULL)
OR (d.[AccountManager] IS NULL
AND i.AccountManager IS NOT NULL)
#marc_s is right, you have to re-construct your trigger and tables. here take example.
you need to put where condition in select #OldName = Name from deleted.
e.g.-
**
CREATE TRIGGER Trg_Institution_FieldAudit ON Table1 FOR UPDATE
AS
DECLARE #OldName VARCHAR(30)
DECLARE #CurrentName VARCHAR(30)
IF UPDATE (Name)
BEGIN
SET #OldName = Table1.Name FROM deleted
WHERE Table1.Name = deleted.Name;
SET #CurrentName = Table1.Name FROM inserted
WHERE Table1.Name = inserted.Name ;
--INSERT statement for old and new values.
END
GO**
After looking for an alternative for FOR EACH in SQL Server, I found that a CURSOR can be used. It serves the purpose, but need somebody to validate this.
CREATE TRIGGER Trg_Institution_FieldAudit_1 ON dbo.Institution FOR UPDATE as
-- DECLARE Variables
DECLARE institution_cursor CURSOR DYNAMIC FOR SELECT * FROM DELETED
OPEN institution_cursor FETCH NEXT FROM institution_cursor INTO -- #variables here
WHILE (##FETCH_STATUS = 0)
BEGIN
IF UPDATE(COL1)
BEGIN
INSERT INTO AuditTable VALUES (COL1, #prev, #next);
END;
FETCH NEXT FROM institution_cursor INTO -- #Variables here
END
CLOSE institution_cursor
DEALLOCATE institution_cursor