.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

After Update trigger for a record which does not exist in table.

Posted By:      Posted Date: May 22, 2011    Points: 0   Category :

Hi Everyone,

I have a update query which sometimes results in no row updated (i.e. 0 rows updated),

I want to apply after update trigger on it , if update results in 0 row affected then insert that record,

I have written following trigger for it,

ALTER TRIGGER [dbo].[table1]

   ON  [dbo].[table1]





            SET NOCOUNT ON;

View Complete Post

More Related Resource Links

execute update timedout expires , table with trigger due to recovery of database


I have table A in database A  , in table A i have trigger to insert record to database B table A, each update and insert of database A -table A, triiger fire and insert record in database B table A, when i try to update some times asp.net application gives error

"Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding."

and then error log says System.Data.SqlClient.SqlException: Database 'database B is being recovered. Waiting until recovery is finished.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean ret

how can insert only new record into another table through trigger

I have on master table in sql in which every time new data is inserted.i just want to copy the new inserted record into another table.How can i do this. below is my trigger but how can it identify only new records should be inserted into second table.please help me and modify it. CREATE TRIGGER CopyRecordToPortInTable ON SmsTable AFTER INSERT AS BEGIN SET NOCOUNT ON; insert into Portintable(smsno,smstext,flag) select (sms,smstext,0) where condition END

Update a record in a table?

HiI've been playing around with MVC lately, and was wondering how you could do this:I have a view that displays a list of products, and against each product is a list of categories (in a combobox). I'm trying to find out how you can update a product's category when you select a category in the list. I know you could do something fairly simple with jQuery, but I'm trying to understand how submitting forms works with MVC.Here's what I currently have:// Controller public ActionResult Index() { List<Product> products = _productRepository.GetProducts(); List<ProductCategory> categories = _productRepository.GetCategories(); ProductsViewModel viewModel = new ProductsViewModel { Products = products, ProductCategories = new SelectList(categories, "Id", "Description") }; return View(viewModel); } // ViewModel public class ProductsViewModel { public List<Product> Products { get; set; } public SelectList ProductCategories { get; set; } } // View <% using (Html.BeginForm()) { %> <table> <tr> <th>Id</th> <th>Description</th> <th>Category</th> </tr> <% foreach (var product in Model.Products) { %> <tr> <td><%: product.Id%></td> <td><%:

SQL Trigger INSERT, UPDATE table name (inserted updated)

I am trying to make a trigger for INSERT, UPDATE.  For INSERT you get a table named inserted that you can use, and for UPDATE you get updated.  But what is the name if you doing a trigger for both?

Updating a table - or add when the record doesn't exist



I'd like to be able to update a table from a VB application without the table being part of the project.

I know how to insert a record:


Dim connectionstring As String = My.Settings.AdminCentreConnectionString

Dim eSQL As String =

how to use DML update trigger to track all table changes


Hi All,

Somebody is making updates to a table that shouldn't be updated!  I've been asked to track which user, the updated column name(s), and the before and after value(s).  It doesn't matter how many or which field(s) had the value updated.  If it was updated, we need to track it.

The straightforward method seems to be using a DML update trigger like the example shown at http://msdn.microsoft.com/en-us/library/ms187326.aspx, but there's over 30 columns in the table that need to be watched.  From the example at that page, it appears I would need a "IF UPDATE(my_col_name)" statement for each and every column we'd like to watch.  Correct?

How would we ID the user that made the change?  I assume there's a variable available within an update trigger that holds that value.

My main question ends there, but here's a little more background that may affect any advice:

1.  We can't track changes in a table.  Instead, they have to be written to the SQL Log, which I've found can be accomplished using "xp_logevent".
2.  A separate log entry for every field updated in a row is not a requirement.  One log entry with a row showing the old values and another row showing the new values would suff

here is trigger if exist then update else inser but not working properly for bulk update(10 or 15 ro



i have a trigger as follows



TRIGGER [ table_detail_insert_update]








update trigger based on value in another table


I would like to create a trigger to stop the update of an existing record, if the date is less than a date for that event type in another table

if the date of the record being updated is < select Date from OtherTable where eventType = (event type of row trying to be updated)

I would still need to do inserts but not updates.

This is my 1st trigger so excuse me if its a really simple thing, but i have googled and dont find anything quite like i think i need

how to get id value from the row inserted in a table with thr trigger.


I have a reports table with column report id and and report version. I created a trigger on this table to execute an application to do some processing each time a row is inserted in reports table. I need to pass the new report id execute this application from the trigger. How do I get the report id from the row that was inserted?


Trying to set update panel trigger programmatically


 I have a recursive sub that finds a dropdown list and sets up an AsyncPostbackTrigger for an update panel. I have tried calling this sub both from page_init and page_load 

If the dropdownlist is within the update panel, eveything works fine. If the dropdown list is not in the updatepanel I get error

A control with ID 'ddlPersonFilter' could not be found for the trigger in UpdatePanel 'up1'. In both cases the sub does find the dropdown list and executes the code to set up the trigger. Thanks for your help.

    Private Sub SetUpdatePanelTrigger(ByVal oControl As Control)
        For Each ctrl As Control In oControl.Controls
            If TypeOf ctrl Is DropDownList Then
                If CType(ctrl, DropDownList).ID = "ddlPersonFilter" Then
                    Dim thisddl As New DropDownList
                    Dim thistrigger As New AsyncPostBackTrigger
                    thisddl = ctrl
                    thistrigger.EventName = "SelectedIndexChanged"
                    thistrigger.ControlID = thisddl.ID
                    Exit Sub
                End If
                If ctrl.HasControls Then
                End If
            End If

Can't perform Create, Update or Delete operations on 'Table(outbox)' because it has no primary ke



I'm a beginner in asp.net and I have some problem inserting data into sql server 2005 with linq.


my code is : 


        Dim Result As New SMS.SendResult
        If Result.status = 0 Then
            Label1.Text = "Your Message Sent Successfuly"
            Dim db As New IGSSDataContext
            Dim out As New outbox With {.ClientID = intRandomNumber, .From = User.Identity.Name, .TO = TextBox1.TabIndex, _
            .Time = Now, .Message = Message}
            out.ID = (ID)
            TextBox1.Text = ""

How can i check if record already exist in sql-server database ...

How can i check if record already exist in sql-server database ...

select max record to join another table sybase

select a.pono,(select (user) from user where userid=a.userid having date=max(date)) as user from a inner join b on a.no=b.no  in the result , i have selected the same id and retrieve two records every thing are same except the date how can i select the record out of two record which date is max date as the where Clasuse to select correct user poid    date                name 1        12/08/2010      Mary 1        20/08/2010      Peter   now i would like to select name which id=1 and date is max and then use the name to join another table because name is foreign key  

Generic Audit Trigger CLR C#(Works when the trigger is attached to any Table)

This Audit Trigger is Generic (i.e. non-"Table Specific") attach it to any tabel and it should work.  Be sure and create the 'Audit' table first though. The following code write audit entries to a Table called'Audit' with columns 'ActionType'    //varchar'TableName'    //varchar'PK'    //varchar'FieldName'    //varchar'OldValue'    //varchar'NewValue'    //varchar'ChangeDateTime'    //datetime'ChangeBy'    //varchar using System;using System.Data;using System.Data.SqlClient;using Microsoft.SqlServer.Server; public partial class Triggers{//A Generic Trigger for Insert, Update and Delete Actions on any Table[Microsoft.SqlServer.Server.SqlTrigger(Name = "AuditTrigger", Event = "FOR INSERT, UPDATE, DELETE")] public static void AuditTrigger(){SqlTriggerContext tcontext = SqlContext.TriggerContext; //Trigger Contextstring TName; //Where we store the Altered Table's Namestring User; //Where we will store the Database UsernameDataRow iRow; //DataRow to hold the inserted valuesDataRow dRow; //DataRow to how the deleted/overwritten valuesDataRow aRow; //Audit DataRow to build our Audit entry withstring PKString; //Will temporarily store the Primary Key Column Names and Values hereusing (SqlConnection conn = new SqlConnection("context connection=true"))//Our Connection{conn.Open();//Open the Connection//Build the AuditAdapter an

update data on table

i have  100000 record  found in the  tha table and  i want  to update the column SocialState when found male he replace  the text male to 1 and when foun Female  he replace the text to 2   update [Drugs].[db_accessadmin].[Data] set SocialState='1' where SocialState='Male' update [Drugs].[db_accessadmin].[Data] set SocialState='2' where SocialState='FeMale' he give me this message "(0 row(s) affected)"

Trigger that deletes another table's row

Hi, I'm new to making triggers. I have the following trigger wich should delete a row in the Activity_Log table when I delete a row in the Poll_Comments table.... I have an error in my where clause - because it don't delete the specific row.... My trigger:ALTER TRIGGER [dbo].[deletePollCommentsTrigger] ON [dbo].[Poll_Comments] FOR DELETE AS BEGIN DECLARE @intRowCount int SELECT @intRowCount = @@RowCount IF @intRowCount > 0 BEGIN DELETE Activity_Log WHERE id IN (SELECT questionId FROM deleted) AND activityDateCreated IN (SELECT commentsCreateDate FROM deleted) AND activitySectionPId = 8 END END If I change the statement to: DELETE Activity_Log WHERE id IN (SELECT questionId FROM deleted) AND activitySectionPId = 8 It correctly deletes all rows with that specific questionId and where activitySectionPId = 8... But I want also to have a where clause on, that ask for commentsCreateDate = activityDateCreated - so I only delete one row and not all rows... How can I do that? Kind regards,simsen :-) 

Delete Record From Table A that Is Not In Table B

I have two tables; Table A id, name 101, jones 102, smith 103, williams 104, johnson 105, brown 106, green 107, anderson   Table B id, name, city, state 101, jones, des moine, Idaho 103, williams, Corvallis, Oregon 104, johnson, Grand Forks, North Dakota 105, brown, Phoenix, Arizona 107, anderson, New York, New York   I need to delete records from Table A that are not in Table B.  My front end is writen in .net and I am using Data Access Layer along with a Business Logic Layer for data interaction.   I have tried at least seven variations of joining, right outer join, left outer join resulting in wiping our the entire table or nothing at all; not to mention deleting the record that ought to remain and keeping the record that needs to be deleted!   In my BLL I tried to capture the rowsAffected for the deletion by using-without success. Dim rowsAffected As Integer = Adapter.ID_Deletion(ID) If rowsAffected = 1 Then Exit Function Else Return rowsAffected = 1 End If   Please help.   MsMe.
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend