hi,CAn i have one trigger for both Update and DeleteDelete Trigger---------------------create Trigger [tr_delete_user_log]on [dbo].[user_log] for deleteasbegininsert into z_user_log select * from deletedendTrigger Update---------------------CREATE Trigger [tr_update_user_log]on [dbo].[user_log] for updateasbegininsert into z_user_log select * from deletedendCan i have one trigger instead of these Triggers ..
I HAVE TWO TABLES IN THE DATABSE AND THE SECOND TALE SI FOR AUDITING. I WANT CREATE THE TRIGGER ON FIRST TABLE SO THAT I CAN PUT THE STATUS LIKE INSERT,UPDATE OR DELETE IN THE STATUS COLUMN IN SECOND TABLE. CAN SOMEBODY HELP IN WRITING THAT TRIGGER..? HOW CAN I DETERMINE WAETHER THE RECORD IS BEEN INSERTED OR UPDATED OR DELETED.
DO I HAVE TO WRITE A SEPERATE TRIGGER FOR EACH ACTIVITY..OR I CAN WRITE IT IN THE SINGLE TRIGGER..?
I have to create a trigger that will log who changed information on a table and when (NOT what they have changed).
My idea is to get the users name and see if it is in a table if not create it and get the associated ID, also get the ID of table that was accessed along with the ID of the type of task that was performed. Take this data and insert it into a table.
Hi everyoneI am trying to create a DELETE Trigger. I have 2 tables. Table1 andTable2. Table 2 has all the same fields and records as Table1 + 1extra column "date_removed"I would like that when a record is deleted from Table 1, the triggerfinds that record in Table2 and updates the date_removed filed withcurrent time stamp.The primary key on both is combination of domain,admin_group and cn.CREATE TRIGGER [tr_updateTable2] ON [dbo].tbl_Table1FOR DELETEASUpdate Table2SET date_removed = getDate()I'm stuck here, how do I manipulate on Table2 only the records thatwere deleted on Table1, so to only update date_removed filed for themin Table2?I guess i need to compare domain, cn and admin_group, but I don't knowhow.Any help would be greatly appreciatedThanks! :-)
I have an c# windows service, which is running on the same machine where my mssql server is installed. This service must be informed for each insert/update/delete event on one specific table.
My idea was to create an CLR Trigger for this table which can communicate with this service via .NET remoting. But the problem is, that the system.runtime.remoting assembly is not integrated within the mssql clr enviroment => i can't use remoting.
I have never used triggers before and I have tried to solve one problem. If I have the column "currency" in a table and want to make sure that the entered value i valid in relation to another table that contains valid currency formats, I did it like this:
--------------------------------- CREATE TRIGGER [trigger_checkCurrency] ON [dbo].[Client] FOR INSERT, UPDATE AS declare @currency as char(50) declare @country as char(50)
declare cur cursor for SELECT currency, country FROMinserted
OPEN cur fetch cur into @currency, @country WHILE @@FETCH_STATUS = 0 BEGIN if not exists(select * from listinfoid where listname = 'currency' and listid = @currency) begin set @currency = (cast(@currency as varchar (3)) + ' is not a valid currency') CLOSE cur DEALLOCATE cur RAISERROR (@currency,16,-1) with log return end if not exists(select * from listinfoid where listname = 'country' and listid = @country) begin set @country = (cast(@country as varchar (3)) + ' is not a valid contry') CLOSE cur DEALLOCATE cur RAISERROR (@country,16,-1) with log return end else fetch cur into @currency, @country
END CLOSE cur DEALLOCATE cur update Client set currency = UPPER(currency), country = UPPER(country) ---------------------------------
I use a cursor to handle multiple rows in an update query. (SQL2000-server)
Is there an easier och better way to do this? I´m a bit unsure of this code.
Hello, I recently view a webcast of sql injection, and at this moment I created a user, and give dbo to this user, and this same user, is the one I have in the connection string of my web application, I want to create a user to prevent sql injection attacks, I mean that user wont be able to drop or create objects, only select views, tables, exec insert,update, deletes and exec stored procedures.
Is any easy way to do this?
A database role and then assing that role to the user?
how to do this i have table of employee ,evry employee have a unique ID "empid" empid VAL_OK -------------------------- 111 0 222 0 333 0
now insert multiple insert to my work_table shifts for all month for evry employee like this (this is work_table) empid date val -------------------------------------------------- 111 01/02/2008 1 111 02/02/2008 2 ............... 111 29/02/2008 5 --next employee 222 01/02/2008 1 222 02/02/2008 4 ............... 222 29/02/2008 6 --next employee 333 --next employee 444 --next employee 555 -------------------------------------------------------------
now i need for evry OK insert (for all month) each employee go to the TB_Employee and update each employee once !! from VAL_OK=0 to VAL_OK=1 like this
empid VAL_OK -------------------------- 111 1 222 1 333 1 ---------------------- like this i know who is the employee have shift for all month and who NOT !
i think it like this
Code Snippet Create trigger for_insert on tb_work For insert begin if @@rowcount = 1 Update tb_employee Set val_ok= 1
else /* when @@rowcount is greater than 1, use a group by clause */ Update tb_employee set val_ok= 1 select empid from tb_work group by tb_work.empid
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!
HelloI have a Trigger on a table. Here is the code ALTER TRIGGER [dbo].[OnOrderDelete] ON [dbo].[orders] AFTER DELETE,UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @ids int; SELECT @ids =( SELECT id from DELETED); DELETE FROM files WHERE OrderId = @ids; ENDActually the UPDATE event handler is not wanted here, but why when I leave him I have a following behaviour:When orders table is updated, the "SELECT @ids =( SELECT id from DELETED); DELETE FROM files WHERE OrderId = @ids;" part is executed, and the program recognizes DELETED as UPDATED! (Like " SELECT @ids =( SELECT id from UPDATED) ") Is this right? And how can I part UPDATED and DELETED ?ThanksArtashes
I have a table where I want to prevent user from deleting or setting a flag on a field to "y" with a database trigger (sql 2000). I understand the trigger for just one (stopping the delete, or stopping the field being changed to "y"). Should I have 2 seperate triggers or would there be a way to handle both.
In SQL Server 2005 Express I created a trigger which should edit a value in another table when a special tupel column has been updated. The funny thing is, that it also fires on delete...of course not what I wanted. what did I do wrong?
Thanks in advance!
ALTER TRIGGER dbo.update_history_users
ON dbo.[user]
AFTER UPDATE
AS
IF UPDATE([name])
BEGIN
DECLARE @old_value nvarchar(MAX),
@new_value nvarchar(MAX);
SELECT @old_value = name FROM DELETED ;
SELECT @new_value = name FROM INSERTED ;
UPDATE dbo.history SET user_name = @new_value WHERE user_name = @old_value;
I am having problems with a trigger that is designed to audit changes to a particular field in a table. If that field is updated, then the old record is inserted into an audit table.
This trigger never fails when I run test data against it from Query Analyzer. It works some of the time when the web application updates it, fails other times.
Typically, multiple records are updated at the same time. Any ideas?
Here is the Trigger:
create trigger t_u_product_rate_detail on product_rate_detail for insert, update, delete
--Set values so function isn't executed a bunch of times select @auditdate = getdate(), @audituser = suser_sname()
if exists (select * from inserted) begin if exists (select * from deleted) begin insert into product_rate_detail_audit_log select d.product_rate_detail_id, d.product_rate_id, d.day_of_week_id, d.ad_size_id, d.rate, d.plan_vol, d.plan_freq, @auditdate, @audituser, 'U' from deleted d join inserted i on i.product_rate_detail_id = d.product_Rate_detail_id where (d.rate <> 0 and d.rate is not null) and i.rate <> d.rate -- this determines if the rate has changed. end end
GO SET QUOTED_IDENTIFIER OFF GO SET ANSI_NULLS ON GO
I have a question about trigger. I have a table called "Users", it has a ID (auto increment), UserName, FirstName...ect. The question is if one row is deleted, I want to put this row into "Users_Histroy" Table whose structure is the same as "Users" Table and then delete this row in "Users" Table.. How can I achieve this? I am pretty new about triggers. Thank you very much.
I have 3 tables...TableA, TableB, TableC TableA - Personal InformationPersonalInfoId (Primary) , First Name,Last NameTableB - Personal Information To Department IDReferenceID, FKPersonalInfoId, FKDepartmentIdTableC - DepartmentDepartmentId, DepartmentNameI am coding Asp.Net VB using VWD express with Sql Server Express. I know how to create a stored procedure to delete, insert and even update a record in TableA, TableB, TableC respectively.If I need to delete a record in TableC, which has a related record in TableB, I have read that I need to use a Trigger. I never have used a Trigger and it is new to me. Can someone point me a way on how to use one in this case of my deleting scenario. Pretty much, if a user clicks on a delete button, and deletes a record in my TableC, I dont want a FKDpartmentId in my TableB that doesnt exist anymore because it was deleted in TableC or prevent a user from deleting that record till the relationship in TableB is no longer valid. In the same vain, If I have a input form which ask the user to enter their First Name and Last Name and Department, i would like to add those records in TableA for First and Last Name, TableB for the Department. Once again, how do I create a Trigger that if I insert a record in Table A to also insert the information for Department in Table B, if its successful in my stored procedure. Hope that made sense.Thanks.
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).
Hi, I have a table with somefields, here i will only mention on which i need to perform an action, possibly with the use of Trigger.
Fields = Active, inactiveDate Active Field is of bit datatype mean conatins 1 or 0, 1 means the user is active, but when i change the active field to 0, and make the user inactive i want the date to be populated automatically to inactiveDate field when active field is changed to 0.
I have one table named as "Order", and other table as "Shipment". Now, I want to check if one column name "Status" in the "Örder" table has been changed (when it becomes status = 7) then I need to insert records in "Shipment" table.
Order Table: OID===Order_Product===Order_Description===Order_Status
But it inserts the records into Shipment Table every time the status field or any other field in the Order Table is changed. What I want is that, "When Status Column in Order Table is Updated to 7, then insert record in Shipment Table".
Hi All, I have this project I'm working on it's Product Content Management System rewrite. I got to the point of updating the Product By Sku and not sure if I should use UPDATE statement or I should DELETE sections assosiated with the ProductContentID and then re-insert them again? I'm not sure which is more afficient? I can really do both and it's really not that complicated, the only problem I see with DELETE then INSERT is the ProductContentSectionId in the Sections table is going to grow very fast and I'm a bit concerned about it. We use SQL Server 2000 and we have about 4 bound tables where we keep the data. The one I'm talking about is the sections table where we keep the actual types of product content like a BoxShot, Description, Key Features and so on... Thank you in advance! Tatyana Hughes
I am trying to update a SQL database with data from a Wang system. The Wang data is dumped to a txt file. I then import it into an update table in SQL via Access. Some of the data is new and some of the data is updated records. At this point I have been trying to create a script to update and add data to a table via the query tool in SQL Then delete data from the update table.
I was able to get the UPDATE and DELETE to work but I have not figured out how to insert new records at the same time? Can I use an IF statement? I will apreciate any help or sample code, Thanks.
UPDATE MemberList Set Name = NameUpd, Address1 = Address1Upd, Address2 = Address2Upd, City = CityUpd, State = StateUpd, ZipCode = ZipCodeUpd, MemberStatus = MemberstatusUpd FROM MemberList, MemberListUpd WHERE MemberList.MemberNumber = MemberListUpd.MemberNumberUpd
I vaguely recall reading an article that I can no longer find that an update statement is executed as a combination of a Delete and an Insert by SQL server. Does anyone know if this a still a true statement in SQL Server 2005?
help on CREATE stored procedure delete and after insert where not exist in one stored procedure in table_B
Code Snippet CREATE PROCEDURE [dbo].[delete_from_table_B] @empID varchar(500) as DELETE FROM table_B WHERE charindex(','+CONVERT(varchar,[empID])+',',','+@empID+',') > 0
---HELP from this ponit how to insert ? after where not exist
IF @@ROWCOUNT > 0
BEGIN
insert into table_B set (empID,ShiftDate,shiftType) where not exist
Hi - I know my way around VS but I am just exploring "advanced" SQL Server 2005 and have run into a challenge which I think a trigger could solve, but I am not sure and also don't know how to set that up. So any help or links to tutorials are highly appreciated. Here is the challenge: I have a table with a number of fields, among them RequestID (bigint) and Booktime (datetime). What I would like to happen is whenever someone writes a value different from NULL into RequestID, Booktime gets set to the current timestamp. When RequestID gets set to NULL, Booktime gets set to NULL. Is there a way to do this with a trigger (or an otherwise elegant way)? Thanks in advance for ANY help or ideas. Oliver
I'm using DataAdapter.Update() to update data in a table. My question is; how do I create a trigger that works after the update has completely finished?
For example if my update adds 50 new rows to a table the trigger I've currently got fires after each new row that is added ie 50 times in total. Is it possible to get it to trigger after the last (ie 50th) row is added???
IF EXISTS ( SELECT * FROM empList WHERE (unit = 9)
) begin
update [dbo].[empList] set unit = CASE WHEN SELECT na,empID, unit FROM empList WHERE (empID IN (111, 222, 333, 555)) AND (unit = 9)) then '4' else t.fld1 end
for now, doing a small school project, i find doing SPs for Insert useful, like checking for existing data and not inserting, that might not be the best method, i had advice from here i can use unique constraints instead, then what about update and delete? SPs also? the pros make SPs for everything? currently use dynamically generated SQL from SqlDataSources. for Update / delete. some delete are SPs too...
I have recently started an ASP.Net application and am having some issues updating, inserting and deleting rows. When I started working with it, I was getting errors because it could not find any update command. Eventually, I figured out how to automatically generate the commands, by configuring my SQLDataSource control and clicking the "advanced" button. Right now though, I have generated the commands, but I still can not insert, update or delete rows. When I attempt to update anything, I recieve an error that says "The data types text and nvarchar are incompatible in the equal to operator." Nowhere in my table do I have any rows that use the datatype "nvarchar", only "text" and "int". I tried switching all of my text columns to "nvarchar(500)", which did not help. I am led to believe that the auto generated SQL procedures are trying to do something behind the scenes that is making my database act up, because even when I delete rows, I get the same exception, so the datatypes cannot be messed up there, because all that the datasource is doing is deleting rows, therefore there is no need to worry about data types. I only get the error when I check the "Use optimistic concurrency" box. When I do not use optimistic concurrency, I can delete, insert, and update rows... but nothing happens. There are no errors, but nothing is deleted, updated or inserted either. Upon postback, nothing has changed. I may upload a copy of the exact exception page, if someone thinks that it may help. Here is the update command that was generated: UPDATE [Record Information] SET [Speed] = @Speed, [Recording Company] = @Recording_Company, [Year] = @Year, [Artist] = @Artist, [Side 1 Track Title] = @Side_1_Track_Title, [Side 1 Track Duration] = @Side_1_Track_Duration, [Side 2 Track Title] = @Side_2_Track_Title, [Side 2 Track Duration] = @Side_2_Track_Duration, [Sleeve Description] = @Sleeve_Description WHERE [Record Database ID] = @original_Record_Database_ID Apparently no stored procedures exist for any of these operations, and I am unsure why. The "Record Database ID" is my identity column, and is the only field that is (and is supposed to be) uneditable.
Hi,I just upgraded my ASP.NET 2.0 BETA 2 environment to the final release of ASP.NET 2.0 VWD.Once the update was finished, I could open my website without any problems..... Now, I noticed that in the final release, some modifications have been included in the Membership Stored Procedure and other stored procedures. So I created a new database (SQL Express) and added my data again.After re-creating my SQLDataSources, I tryed to enable the Editing and Deleting option in VWD and once I run my web application, it seems when selecting editing and then update, it doesn't work anymore....This is my code : <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:IMMOASPNETDBConnectionString %>" DeleteCommand="DELETE FROM aspnet_test WHERE (testID = @Original_testID)" SelectCommand="SELECT BuyID, BuyNL, BuyFR, Lastupdated FROM aspnet_Buy" UpdateCommand="UPDATE aspnet_Buy SET BuyNL = @BuyNL, BuyFR = @BuyFR WHERE (BuyNL = @original_BuyID)"> <DeleteParameters> <asp:Parameter Name="Original_testID" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="BuyNL" /> <asp:Parameter Name="BuyFR" /> <asp:Parameter Name="original_BuyID" /> </UpdateParameters> </asp:SqlDataSource> <br /> <br /> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="BuyID" DataSourceID="SqlDataSource1"> <Columns> <asp:CommandField ShowEditButton="True" /> <asp:BoundField DataField="BuyID" HeaderText="BuyID" InsertVisible="False" ReadOnly="True" SortExpression="BuyID" /> <asp:BoundField DataField="BuyNL" HeaderText="BuyNL" SortExpression="BuyNL" /> <asp:BoundField DataField="BuyFR" HeaderText="BuyFR" SortExpression="BuyFR" /> <asp:BoundField DataField="Lastupdated" HeaderText="Lastupdated" SortExpression="Lastupdated" /> </Columns> </asp:GridView>Can someone help me with this ? What is wrong with the Update command ?Thanks to all,Bart