SQL Server 2005 Trigger Fires Per Statement Or Per Record
May 3, 2006Hi
In SQL Server 2005, does TRIGGER for DML fire per statement or per Record ?
If both, can we define the way it should fires.
thanks / ramanuj
Hi
In SQL Server 2005, does TRIGGER for DML fire per statement or per Record ?
If both, can we define the way it should fires.
thanks / ramanuj
Dear Experts,I'm an Oracle guy, who is being given more SQL Server assignmentslately.I've been looking for things on the web about this, but I can'tanything so far.In Oracle, I you can create a trigger on a table that -only- fires ifcertain fields are updated.create or replace trigger trg_some_triggerBEFORE insertOF some_field1, some_field2on tbl_some_tablefor each row....Is this also possible in SQL Server?What is the syntax please?Thanks a lot!
View 2 Replies View RelatedIf I update a record such as
Update MyTable SET MyField = 'MyValue'
where MyKey = 'Key1'
The trigger fires .....
If I update multiple records
Update MyTable SET MyField = 'MyValue'
where MyKey IN ('Key1','Key2')
Does the trigger (Update) on MyTable fire more than once or once.
hi,
I want a trigger in db aaa to fire when table a_aaa is updated in server a and table b_bbb in db bbb in server b to be populated with data. I know how to write a trigger if fired and the result stays in one server with one db. But I don't know how to do it if between two servers and two db.
a
win server 2003 standard Edition
sql Server 2000
db:aaa
table: a_aaa
column:a_aaa_a
b
win server 2003 standard Edition
sql Server 2000
db:bbb
table:b_bbb
column: b_bbb_b
It's not working because the symtax is incorrect and because I am not sure how to do it between two servers. If it is not correct, where am I wrong? Where should each line be located?? et cetera......
Can anyone help?
Thanks in advance.
CREATE TRIGGER [enddate_changed_on_alert] ON [dbo].[USER_DATA]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @EndDate as DATE
DECLARE @CompCode as VARCHAR(15)
DECLARE @PhoneGMSM as VARCHAR(10)
DECLARE @PhoneALERT as VARCHAR(10)
SELECT @PhoneALERT=phone1 from AUSSMEDEVIQ1.QDB_Test.USER_DATA;
SELECT @PhoneGMSM=PHONE1 from AUSADFORMULA02.QDB_KS.dbo.USER_DATA_DEVIQ;
UPDATE AUSADFORMULA02.QDB_KS.dbo.USER_DATA_DEVIQ SET EXT4 = "111"
WHERE AUSSMEDEVIQ1.QDB_Test.USER_DATA.@Phone = AUSADFORMULA02.QDB_KS.dbo.USER_DATA_DEVIQ;
WHERE:
USER_DATA_DEVIQ = b_bbb_b
AUSADFORMULA02 = bbb
QDB_KS = b_bbb
USER_DATA = a_aaa_a
AUSSMEDEVIQ1 = aaa
QDB_Test = a_aaa
END
GO
I have an update trigger that works wonderful as long as I am updating the row in Enterprise Manager, but if I update the same column and row using an update statement in Query Analyzer the trigger doesn't fire.
Any ideas why?
TIA.
Need to parsing serverName and databaseName to run a dynamic query to get serverName and databaseName and employee_ID via a accountID parameter.
-----------------------------
declare @stringSQL varchar(200)
select @stringSQL=
'insert into temp1 select '+@AccountID+' accountID, employee_ID from ' + @serverName +'.dbo.'+@databaseName+'.tblEmployee where inactive=0'
print @stringSQL_GetUserName
exec (@stringSQL_GetUserName)
select * from temp1
------------------------------
above dynamic query works fine.
Howevery, this should be run only under insertion event. When I put it in a proc to run within the insertion trigger or put the whole sql statement within the trigger:
1. when ran at a MSDE server
MSDTC on server is unavailable.
2. when ran at a SQL2000 developer testing server with the distributed transaction coordinator on, the insertion a record in the isql/w hang there. Could not even to kill this query, and have to stop and restart the SQL server.
Then I just want to return the dynamic query result without 'insert into temp1 ', the result is still hang...
Is there a way to let the insert trigger to run a dyanamic query which linked to around 10 servers?
thanks
David
I am looking to update a record from a previous row. So if there is a value of total goods in week 1, i want that value to carry forward to the value of goods in week 2. Is there any SQL as an example of the best way to accomplish this? I can query it using lag() which works great but i need the source data itself to update as the end-users are accessing the data via lightswitch, so when they save a change, i want the trigger (or whatever you recommend) to update the source table.
View 9 Replies View RelatedI am inserting a record in XYZ table(DB1). Through trigger it will update ABC table(DB2).
I am getting error when doing above thing. What are the roles to be set to user to avoid above problem.
I have two different SQL 2008 servers, I don't have permission to create a linked server in any of them. i created a trigger on server1.table1 to insert the same record to the remote server server2.table1 using OPENROWSET
i created a stored procedure to insert this record, and i have no issue when i execute the stored procedure. it insert the recored into the remote server.
The problem is when i call the stored procedure from trigger, i get an error message.
Stored Procedure:
USE [DB1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
[Code] ....
When i try to insert a new description value in the table i got the following error message:
No row was updated
the data in row 1 was not committed
Error source .Net SqlClient Data provider.
Error Message: the operation could not be performed because OLE DB
provider "SQLNCLI10" for linked server "(null)" returned message "The partner transaction manager has disabled its support for remote/network transaction.".
correct the errors entry or press ESC to cancel the change(s).
What statement do I use, as part of an insert trigger, to insert xml data from the xml database to a flat file database, to check if a record with a specific ID exists to delete first then insert the changed record, instead of adding the changes or an updated from the original xml database.
What I’m trying to do is take the xml formatted data out of one sql server database and insert the data only in that xml into a another sql database. So I can play with the data.
Problem is if the data in the xml is updated or changed for a specific record on the original xml database then the trigger inserts another copy into the created database (which I don’t want).
This is on SQL Server 2008R2.
This is part of my trigger on table T1. I am trying to check if the records inserted to T1 is available in myDB.dbo.myTable or not (destination table). If it is available rollback T1. It does not do that although I insert the same records twice.
-- duplicate record check
SET @step = 'Duplicate record'
IF EXISTS (
SELECT i.myID, i.Type
FROM INSERTED i INNER JOIN
myDB.dbo.myTable c ON i.myID = c.myID
GROUP BY i.myID, i.Type
HAVING (COUNT(*) > 1) AND (i.Type = 'In')
)
BEGIN
ROLLBACK transaction
RAISERROR('Error: step: %s. rollback is done.', 16, 1, @step)
Return
END
What is problem?
here is my trigger that i have right now the only problem is that it deletes the records before copying everything into the db i dont what do delete everything i just whant to catch the updated record and then update the other tables same record in the other db how would i do this:
right now i have this
CREATE TRIGGER test ON [dbo].[TEST123]
AFTER INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0
RETURN
IF (COLUMNS_UPDATED() & 2 = 2)
DELETE FROM pubs..TEST123 WHERE test3 = '300'
INSERT INTO pubs..TEST123
SELECT * FROM TEST123 WHERE test3 = '300'
UPDATE pubs..TEST123 SET test1 = 'X' WHERE test1 IS NULL AND test3 = '300'
UPDATE pubs..TEST123 SET test2 = 'X' WHERE test2 IS NULL AND test3 = '300'
UPDATE pubs..TEST123 SET test3 = 'X'
CREATE TRIGGER test ON [Table_1]
FOR UPDATE
AS
UPDATE [Table_1]
set [Field_1] =SUSER_SNAME()
This trigger update all record, I want to update only the current record which is currenty update. How I cant to this ?
Sorry for my english
Hello,
I have a table with a field that contains the record number. This field is an identity column that is needed to be compatible with old Clipper programs. I've to ensure continuity in the numbering. So I have to update those numbers each time one or several records are deleted. I was thinking of using a trigger but I'm quite novice in this domain and don't know how to do it. Does anyone have a solution for this problem ?
Thank you in advance.
Regards,
mathmax
Hello All,I have 2 tables in a MS SQL DB. Table1 and Table2.LogTable2.Log was a copy of Table1 + an extra column for date_deleted. Ihave 2 Triggers on Table1, Insert and delete. So when a record isinserted into Table1 it's copied onto Table2.log, and when deleted inTable1 the same record in Table2.log is time stamped with time ofdeletion.I would like to have another Trigger on Table1 for update. So if acertain field (not primary key) is updated for a record it is alsoupdated in Table2.log This way Table2.log will always have exactly thesame fields per record as Table1.I'm not sure how to reference the modified records only and updatejust the modified fields...something like...?----------------------------CREATE TRIGGER [tr_updateT_Log] ON [dbo].Table1FOR UPDATEASUpdate Table2.LogSET description = , office =-------------------------------------------------Any help would be greatly appreciatedThanksY
View 2 Replies View RelatedI have a parent table with 27 Columns and Child Table with 37 colums - when even there is an update in any of the columns on Parent or Child table, I require new record inserted into Audit_Parent and Audit_child table. Please help with
SQL Code on Create Trigger and insert records into Audit_parent and Audit_child when an Update occurs on any of the columns.
Insert into AuditParent and AuditChild should occur whenever there is an update on either Parent or child table.
Thanks
:confused:
Am in a small fix. my Trigger is updating my entire table records , i don't want that, i want to update a column in the record that is updated by my application using a trigger that tracks updates on that table.
Is there a way i can track the updated record on my table and then update a field in that record through my TRIGGER?
My database is MSSQLServer2005 Enterprise Edition..
Below is my code
CREATE TRIGGER [TR_Employee]
ON [Test_1_1].[dbo].[Employee]
For UPDATE
Not For Replication
AS
BEGIN
Update Employee set Last_Changed = (select getDate())
END
Go
Yemi
Can anybody help me in writing a SQl trigger to delete a record when inserted after 70 seconds.?
View 20 Replies View RelatedI am trying to create this trigger
CREATE TRIGGER User_Insert ON aspnet_users AFTER UPDATE AS
IF UPDATE (UserId)
insert into users (aspnet_user_id, username)
select au.userid, au.username
from aspnet_users au
where au.userid != users.aspnet_user_id;
Whenever the aspnet_users table has a new user added I want the Userid and username fields from that table inserted into the
the aspnet_user_id and username fileds of the users table.
when creating the trigger I get the following error..
Msg 4104, Level 16, State 1, Procedure User_Insert, Line 3
The multi-part identifier "users.aspnet_user_id" could not be bound.
Hello,
I'm having problems with a CLR Trigger trying to get it to work with SQL Server... and i believe it is because permissions... basicly i want to make my trigger get the name of a newly created database and then look for
a table and then see if is empty... then add some rows... thats all...
I have set my databases as Trustworthy and also i have enabled the "clr enabled" parameter...
i mark my project as "Safe" in the Project properties... and it still doesn't work... do i need to
sign my project..? if so.. how?
i'm clueless...
Thank You.!
Code Block
'Table_1' table
- Unable to create table.
A .NET Framework error occurred during execution of user-defined routine or aggregate "Trigger1":
System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.
The protected resources (only available with full trust) were: All
The demanded resources were: UI
System.Security.HostProtectionException:
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)
at System.Security.CodeAccessSecurityEngine.CheckSetHelper(CompressedStack cs, PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Assembly asm, SecurityAction action)
at Triggers.Trigger1()
.
The statement has been terminated.
In SQL SERVER 2005, how can I get the ID of the record I just insert to table?
I defined a table MyTable, and I insert a record into the table using the SQL below
Insert into MyTable (Name) values ("User Name")
You know the field ID is IDENTITY, so it can not be in Insert SQL, and SQL SERVER will pass a value to it automatically.How can I know the ID of the record I just insert to table?
CREATE TABLE [dbo].[MyTable]( [ID] [int] IDENTITY(1,1) NOT NULL, [Name] [nchar](10) NOT NULL,CONSTRAINT [PK_MyTable] PRIMARY KEY CLUSTERED ( [ID] ASC)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]) ON [PRIMARY]
In Pablo Castro webcast, First Look at ADO.NET 2.0, he mentions the use of UpdateBatchSize which I think would be handy.However, I was not able to get it to work.
Dim t As New Global.System.Data.SqlClient.SqlDataAdapter("Select * from Table_1", Global.System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString1").ConnectionString)Dim d As New Global.System.Data.DataTablet.FillSchema(d, SchemaType.Source)Dim cb As New Global.System.Data.SqlClient.SqlCommandBuilder(t)For c As Int32 = 1 To 10000Dim r As Global.System.Data.DataRow = d.NewRowr("id") = Global.System.Guid.NewGuidr("val") = CType(Rnd(), Int32)d.Rows.Add(r)Nextt.UpdateBatchSize = 100t.Update(d)d.Dispose()t.Dispose()
What ends up showing in Sql Server Profiler (Sql Server 2005) is each Insert being executed in it's own statement:exec sp_executesql N'INSERT INTO [Table_1] ([id], [val]) VALUES (@p1, @p2)',N'@p1 uniqueidentifier,@p2 int',@p1='3793CB5E-3B7A-45E7-9A53-0BD528BB6B07',@p2=1
I think I made this example very simple and yet can't fathom why it won't batch the statements.
I'm somewhat aware of SqlBulkCopy and was very pleased with that speed, but don't think it would handle the Update,Delete,Insert that the SqlDataAdapter.Update would.
Originally started using xsd DataSets until I saw the data tutorials in the Learning section here in which case I copied out the autogenerated TableAdapter classes and fuddling with them to do what I want since batching was not something I saw in TableAdapters.
Does anyone see what I'm missing here?Nathan
I have "sqlGetReservationMembers" datasource in my ascx code and another datasource in 'KillReservation'. As you can see "sqlGetReservationMembers" uses a SELECT command only. I have verified this several times. The 3rd block below is the only place in code-behind where "sqlGetReservationMembers" is referenced. When the "KillReservation" fires I get an error stating "Deleting is not supported by data source 'sqlGetReservationMembers' unless DeleteCommand is specified". I'm confused because I can't see where the 'sqlGetReservationMembers' delete event is being fired. I have removed the datasource and recreated it but the problems returns. What am I missing?
Thanks
<asp:SqlDataSource ID="sqlGetReservationMembers" runat="server" ConnectionString="<%$ ConnectionStrings:SiteSqlServer %>" SelectCommand="sp_GetReservations" SelectCommandType="StoredProcedure"> <SelectParameters> <asp:ControlParameter ControlID="gvMyRides" Name="ID" PropertyName="SelectedValue" Type="Int32" /> </SelectParameters> </asp:SqlDataSource>--------------------------------------------------------------------------------- Protected Sub KillReservation(ByVal RideID As Integer, ByVal MemberID As Integer)
Using Myconnection As New SqlConnection(Config.GetConnectionString("SiteSqlServer")) Dim Mycommand As New SqlCommand("sp_KillReservation", Myconnection) Mycommand.CommandType = CommandType.StoredProcedure Mycommand.Connection.Open() Mycommand.Parameters.Add(New Parameter("@MemberID", TypeCode.Int32, MemberID)) Mycommand.Parameters.Add(New Parameter("@RideID", TypeCode.Int32, RideID)) Mycommand.ExecuteNonQuery() Myconnection.Close() End Using
End Sub----------------------------------------------------------------------------------Protected Sub gvMyRides_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvMyRides.SelectedIndexChanged
sqlGetReservationMembers.SelectParameters.Item("ID").DefaultValue = Me.gvMyRides.SelectedValue Me.gvReservationList.DataSourceID = Me.sqlGetReservationMembers.ID
..More Code..........
End Sub-----------------------------------------------------------------------------------
I am using the tables created by the aspnet_regsql.exe tool for security. Basically, I need to ensure that an account named Administrator is never deleted. I also have a role named administrator, and I need to make sure that Administrator is never removed from the administrator role.Can I create a trigger to ensure that the Administrator is never deleted and that the Administrator is never removed from the Administrator role? I know it will probably be two separate triggers: one on the aspnet_users table and one on the aspnet_usersinroles table.Thanks a lot for the help!
View 1 Replies View RelatedI have a table full of items that have a "date_updated" field. I'd like this field to be set to GETDATE() whenever a record is updated. I've got this trigger:
CREATE trigger tr_cp_shiptos_u on dbo.cp_shiptos for update as
update cp_shiptos set date_updated = GETDATE()
Problem is, of course, there's no WHERE clause..yet. I don't know how to refer to the record that was updated.... for example:
CREATE trigger tr_cp_shiptos_u on dbo.cp_shiptos for update as
update cp_shiptos set date_updated = GETDATE()
where shipto_id = @THIS_ID
I imagine there's some kind of builtin variable or something like that. How is this done?
Thanks in advance.
Hi There, I have created a trigger which supposingly will do event before delete the record from its own table.unfortunately when i try delete the record to test it whether it will do the event (inserting some records to another table), i found that it was not doing the event like i wanted to be. :(the trigger is as below :=======================CREATE TRIGGER TG_D_AGENT ON dbo.AgentFOR DELETEASbegindeclare @vAgentID as numeric,@vAgency as varchar(50),@vUnit as varchar(50),@vAgentCode as varchar(50),@vName as varchar(50),@vIC as varchar(14),@vAddress as varchar(100),@vContactNumber as varchar(50),@vDownlink as varchar(50),@vGSM as varchar(10),@vAM as varchar(10),@vDeleted_date as datetime set @vDeleted_date = convert(datetime, convert(varchar(10) , getdate(),103),103)declare cur_policy_rec CURSOR forselect AgentID,Agency,Unit,AgentCode,[Name],IC,Address,ContactNumber,Downlink,GSM,AM from insertedopen cur_policy_recfetch from cur_policy_rec into @vAgentID,@vAgency,@vUnit,@vAgentCode,@vName,@vIC, @vAddress,@vContactNumber,@vDownlink,@vGSM,@vAM WHILE @@FETCH_STATUS=0BEGIN INSERT INTO [Agent_history] (AgentID,Agency,Unit,AgentCode,Name,IC,Address,Con tactNumber,Downlink,GSM,AM,Deleted_date) VALUES(@vAgentID,@vAgency,@vUnit,@vAgentCode,@vNam e,@vIC,@vAddress,@vContactNumber,@vDownlink,@vGSM, @vAM,@vDeleted_date)fetch from cur_policy_rec into @vAgentID,@vAgency,@vUnit,@vAgentCode,@vName,@vIC, @vAddress,@vContactNumber,@vDownlink,@vGSM,@vAM enddeallocate cur_policy_recend===============================in oracle , i normallly can do something like this...====================================CREATE TRIGGER TG_D_AGENT ON dbo.AgentBEFORE DELETE ON dbo.Agent FOR EACH ROWbeginIs that such thing function like 'BEFORE' in MS SQL SERVER 2000, coz in sql server im not sure they do have or not. Plz someone help me on this...realy appreciated if can!
View 1 Replies View RelatedDoes anyone have a stored procedure for sending an email (using SQLMail) when a new record is added to a database table?
I have SQLMail all setup, I just need a good example of a stored procedure or trigger that will sending an email with the details for a new record entry into a table.
thanks!
I need a trigger to set the creation date of a new record in the database... I tried the following, but it changed all records, not just the new one...
CREATE TRIGGER trgCreationDate
ON [dbo].tabCustomerLookup
FOR INSERT
AS
BEGIN
UPDATE tabCustomerLookup
SET CreationDate = getdate()
END
I am new to SQL and these forums, so please bear with me :)
My basic question is if I can create a update trigger that will pull info from another record in the same table if data in certain fields match the existing record.
An example:
The user creates a new record. If said user enters data in specified fields that matches data in the same fields in another record in the same table, can a update trigger be used to fill out the rest of this record with the data from the record that matches?
If you need more Info on my problem, ask and I will try to explain better. There may be a better way of doing this than using a trigger, but I am not sure. The fields that I would use to match the data would not be the primary key fields.
Thanks!
I'm hoping one of you will be able to help me because I haven't had very good luck finding any information on this.
I'm kind of new to SQL, but I'm learning as much as I can.
I created a web form that sends a new record to a SQL 2005 table I setup.
This all works exactly as it should, but I would like to have an email sent out every time a record is added to this table.
I have SQL Mail setup and I ran a test and it worked, but I can't seem to find any info on how to create a trigger that will send an email to me when a new record is added to the table.
My Database is called Engineering
The table is called ESSPartNumLog
And I have the following Columns that I would like to send in my email..
ESSSequence (PK,int, not null)
MaterialType (nvarchar(255, null)
ESSPrefix (nvarchar(255, null)
PartDescription (nvarchar(255, null)
Project (nvarchar(255, null)
PM (nvarchar(255, null)
Any ideas, or can you point me in the right direction?
Im using a trigger to check updates on particular table and execute a email. it works but it doesnt show the right record
im looking into one table called SiteInfo.
here is my code
Im using sql 2005, can someone look at my code or the select statement.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE TRIGGER TTSUpdate
ON SiteInfo
FOR UPDATE
AS
declare @SiteID varchar(10)
declare @Body2 varchar(2000)
declare @Sitename varchar(50)
declare @TTSCreate varchar(30)
declare @TTSCreator varchar(50)
declare @Subject2 varchar (100)
SELECT @SiteID = SiteID,@Sitename = AccountName,@TTSCreator = TTSOwner,@TTSCreate = TTSCreatedDate
from SiteInfo
SET @Body2 = 'New TTS site created: ' + @Sitename + ' With TTS Site ID:' + @SiteID + ' TTS was created on: ' + @TTSCreate + ' By:' + @TTSCreator
SET @subject2 = 'New TTS site created: ' + @Sitename
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'TTSAdmin',
@recipients = 'email address here',
@subject = @subject2,
@body = @body2
GO
When the database starts,I want to startup a trigger to do something,how can I do ?
I know there are two kinds of trigger in SQL Server 2005 ,one is DML trigger and the another is DDL trigger
Could you tell me ,Is there a trigger for database level in SQL Server 2005 ?
I know there is this kind of trigger in oracle .
Hello,I have a form in a web application. When I submit the form it inserts the record into the SQL Server 2005 database. I have an insert trigger. My question is how can i debug the trigger? the trigger then calls a CLR based stored procedure, again how can i debug this CLR stored procedure which gets called by the trigger. Thanks...kindly advice.
View 2 Replies View Related