Creating Triggers On System Tables!!

Feb 27, 2002

Does anyone know if it's possible to create a trigger on the sysdatabases table in the master database? I keep getting permission denied which I'm not sure is right.

View 2 Replies


ADVERTISEMENT

Creating Triggers On System Tables

Mar 1, 2002

Hi,

Does anyone know of a way I can create a trigger on a system table (say sysdatabases in master). I know this is not supported but presumably there's a way it can be done by referencing it's equivilant in Information_schema somewhere.

I'm trying to write a script that will automatically set up a backup schedule for a database that has just been created. I was hoping the trigger would query the sysdatabases table for new database name entries, log necessary info in an audit table and then call a backup script to set up the schedule. Any ideas??

Thanks

Rob

View 1 Replies View Related

Triggers Against System Tables SQL 7

Apr 20, 1999

I'm thinking of building a trigger against a system table(sysobjects) in
database(a) on server(a) that will assist me in updating a table in
database(b)on server(b). What I need to know from table(b)is if a new table
has been added and removed from database(a) on server(a). I want to use a
store procedure to query the table(b). I was thinking of building a trigger
against my sysobjects table that would update table(b) whenever any tables
are added or removed from database(a). Has anyone built triggers against
system tables? I am running SQL 7.

View 2 Replies View Related

How To Write Triggers On System Tables?

Apr 15, 2008

How can we write triggers on system table dbo.sysobjects,
when i tries to write a trigger, it is giving an error that permission is denied.
I even give a permission of "allow modifications to system catalogs" in Enterprise manager.
still it is not giving permission.
How can i create a trigger on dbo.sysobjects table?

View 9 Replies View Related

Query System Tables For Triggers

Apr 24, 2008

Hello,

I am trying to create a stored procedure that will disable triggers on any given table. Basically I want to pass in a table name as a parameter and query the master table for all triggers that belong to that table...then disable them. I just don't know how to get a list of triggers that belong to a table?

Thanks,
Andrew

View 2 Replies View Related

System Table Triggers???

Aug 10, 2001

I would like to put an insert trigger on sysdatabases. Is this possible?

Thanks!

View 1 Replies View Related

System Event Triggers

Jul 24, 2006

Hi, I have several independent, system components that write auditevents to a database locally via ODBC and remotely via TCP, and I havea requirement to audit when the database is available for modification.First, does SQL Server have a concept of starting/stopping specificdatabase instances? Or does my database instance "stop" only when theNT service MSSQLSERVER stops?Second, Oracle has system event triggers, e.g. AFTER STARTUP, but Ican't find an equivalent in SQL Server 2000. What alternatives arethere?Note that I can't rely on the MSSQLSERVER start/stop events in the NTApplication Event log, as the events need to be inserted "in-band" intomy database's event table.TIA,Josh

View 1 Replies View Related

Creating Triggers

Oct 25, 2007

I have never work with triggers before, so I need a hand on how to create a trigger when a row is updated on a table. Lets says I have this table call "Events" and I want to send the new row to another table call "History". When a new row is inserted I want to select that row and inserted in the History table. Can someone give me a hand with this?
 
Thanks,
Erick

View 18 Replies View Related

Creating Triggers(urgent)

Jan 9, 2002

Hi Guys,
I have a requirement to create update,delete triggers in all the columns of each table in my development database. I would really appreciate if anyone could guideme or send me the script.
Thaks a lot for your consideration
Jay

View 1 Replies View Related

Creating Triggers Question

Jul 2, 2001

Hi,

I'm new to triggers, does anyone know any good resources/articles about creating triggers?

I need to create a trigger for table X, to check BEFORE the update of the table whether a double value for column [X].[Y] exists, if it does (and the value is NOT NULL), do not allow update, if it doesnt allow update/insert statement. This is different from unique keys because as I understand, SQL Server doesnt support multiple NULLs.

Thanks everyone!

Ilya Zherebetskiy
Brainlink Development
http://www.brainlink.com

View 1 Replies View Related

Determining What Are System Objects In Sp_help Or System Tables

Jul 20, 2005

Hi,I have a few things on my databases which seem to be neither true systemobjects or user objects - notably a table called 'dtproperties' (createdby Enterprise manager as I understand, relating to relationship graphingor something) and some stored procs begining with "dt_" (some kind ofsource control stuff, possible visual studio related). These show up whenI use"exec sp_help 'databaseName'"but not in Ent. Mgr. or in Query Analyzer's object browser, and also notin a third party tool I use called AdeptSQL. I am wondering how thosetools know to differentiate between these types of quasi-system objects,and my real user data. (This is for the purpose of a customized schemagenerator I am writing). I'd prefer to determine this info with systemstored procs (ie sp_help, sp_helptex, sp_...etc) but will dip into thesystem tables if needed.Thanks,Dave

View 1 Replies View Related

Merge Replication Corruption (system Triggers And Views)

Sep 21, 2006

All of a sudden none of our merge replications are working. In fact you can't even insert, update or delete and data from the tables in the merge publication. When trying that, we get an error stating:

Msg 550, Level 16, State 1, Procedure MSmerge_ins_E3F43EF8B259476099BBB194A2E1708C, Line 42
The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.
The statement has been terminated.

Currently, the only solution I've found is to delete the publication and recreate it. I'm trying to figure out why this happened. It happened on a development server that to my knowledge, hasn't been changed in a week or so outside of changing the server's IP address. Would that cause such an error to occur?

-mike

View 5 Replies View Related

Creating Multiple Triggers Is Same Sql Script

Jun 14, 2004

I'm trying to use Query Analyzer to create several triggers on different files in the same sql script file. It appears to only allow me to create one trigger at a time in Query Analyzer. How do you separate multiple create trigger statements? Here what I'm trying to do:

CREATE TRIGGER PO_BOL_DELETE ON dbo.PO_BOL
FOR DELETE
AS

INSERT into PO_Back
SELECT *, host_name(), suser_name(), getdate()
FROM deleted
GO

CREATE TRIGGER RECEIPT_DELETE ON dbo.receipt
FOR DELETE
AS

INSERT into receipt_Back
SELECT *, host_name(), suser_name(), getdate()
FROM deleted
GO

View 6 Replies View Related

Creating Triggers Among Multiple Database Servers

Nov 14, 2000

Hello,

I am trying to create a trigger to update a table on a different database server. (Both databases are SQL server 7.0) Does anyone know the syntax of how to implement this?

Any help is appreciated!!
Thanks,
Lisa

View 1 Replies View Related

Creating Triggers Using Managed Code In SQL Server 2005

Mar 6, 2008

Hi all( Create a VB 2005 SQL Server Project ) 

i want to Create a Trigger using Managed Code in VB.Net (.NET CLR integration with SQL Server.)Somebody help me.Thanks

View 2 Replies View Related

Creating Triggers In Transactional Replication On The Subscriber Side

Jun 17, 2007

Hi all

i have setup default transactional replication using locat distributor scheme. I need to create triggers on tables at subscriber side. Can this be done using transaction replication?



Thanks,

Arslan.

View 2 Replies View Related

Creating System DSN For SQL Server

May 14, 2008

Hello All
how to dynamically create ODBC DSN For SQL Server with SQL Authentication
 
Thanks in Advance
 
Regards
Balagangadharan.R

View 1 Replies View Related

Triggers Between 2 Tables

May 18, 2003

Hello, everyone. I am sorry I haven't been around for long but I have got this confusion. I haven't been able to set triggers between 2 tables.

I have got a set of data in 1 table and another set in the other table. I want to set the trigger by comparing the data column from one table to another.

All I want to know is is ti possible to do it? Because I have been told that I can only set triggers on only one table.

Any help is much appreciated.

Thanks in advance.

View 1 Replies View Related

Creating System Stored Procedure In 7.0

Mar 14, 2001

Can I create system stored procedure in sql 7.0?
After I used 'alter' to modify a system sp, it's category
change from 'system' to 'user'. Is there way to change it back?
Thanks a lot!

Xiao

View 1 Replies View Related

Audit Tables And Triggers

Jul 23, 2005

Dear Group,I would like to create an audit table that is created with a trigger thatreflects all the changes(insert, update and delete) that occur in table.Say I have a table withSubject_ID, visit_number, dob, weight, height, User_name, inputdateThe audit table would have .Subject_ID, visit_number, dob, weight, height, User_name, inputdate,edit_action, edit_reason.Where the edit_action would be insert, update, delete; the edit_reason wouldbe the reason given for the edit.Help with this would be great, since I am new to the world of triggers.Thanks,Jeff

View 1 Replies View Related

Synchronize Two Tables Using CLR Triggers

Feb 14, 2008

Hi,

I have decided to use CLR Triggers to synchronize data between two different tables but I have a problem. The scenario is this. I do an insert in Table1. Table1 firest the trigger which then inserts a record in Table2. The trigger in Table2 fires a trigger which does an insert to Table1 again.

I need to find a way to disable the trigger so that it will not go in an infinite loop when I insert a record in either of the tables. What I have done so far is to disable Table2's trigger before I commit my insert to Table2 so that Table2's trigger won't fie. I will then enable the trigger after the insert is committed. Also, I have a webservice which manages the inserts/updates/deletes. I call webmethods from this webservice in my clr triggers.

Help please!

Thanks,

Ryan

View 5 Replies View Related

Approach To Creating A Procedure That Contains Dll , Dml To Upgrade A System

May 15, 2007

Hi.I am between beginner and intermediate level of knowledge of sql server.I am dealing with an sql server 2005 situation (oracle also but thats anotherthread/story).I need to assemble a process that an end user can use easily to update adatabase. The update consists of some column lengthening, checks to make surenew data will fit in columns after the ddl is executed, and then generatingnew data (changing primary key column data and keeping all the referingobjects/rows in sync). I also don't want to have an error leave things in abad state.I'm wondering if there is anything special to look out for, and if there areany suggestions on approach. Here is my current approach:write a single stored procedure to do all the work.have it check for existence of table01_bak and table02_bakdelete them if they existrecreate themcopy table01 and table02 to table01_bak and table02_bakcalculate the new primary key values neededmake sure they will fit (I need to bail out and tell the user to make anadjustment at this point if they will not)start a transactiongenerate the new primarky key values and insert themupdate all the other tables that refer to the still existing primary keys topoint them to the newly generated onesdelete all the old rows using the original primary keyscommit a transactiondelete the table01_bak and table02_bakthanksJeffJeff Kish

View 3 Replies View Related

Creating System Dsn To SQL Server 2000 Sp 4 Fails

Jul 23, 2007

Hi,



I hope someone can help me out here? I have a fresh install of SQL Server 2000 (standard edition - sp4), on a server running Windows 2003 SE (v 5.2.3790). I am trying to create a system dsn on my client pc (running Windows 2000) to a newly created database in SQL server called BLISS.



I am getting the following error message:



Connection failed:

SQL State :'01000'

SQL Server Error: 11001

[Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]Connection Open (Connect()).

Connection Failed:

SQL State :'08001'

SQL Server Error: 6

[Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]Specified SQL server not found.



From support.microsft.com I have tried changing the TCPPort value to 0, but this has not helped. Does anyone have any further ideas please?



Jackie

View 5 Replies View Related

Triggers-Inserted/Deleted Tables

Mar 22, 2000

I am reading the WROX "Professional SQL Server 7 Programming" book.
The following code appears on page 424:

CREATE TRIGGER ProductIsRationed
ON Products
FOR UPDATE
AS
IF EXISTS
(
SELECT 'True'
FROM Inserted i
JOIN Deleted d
ON i.ProductID = d.ProductID
WHERE (d.UnitsInStock - i.UnitsInStock) > d.UnitsInStock / 2
AND d.UnitsInStock - i.UnitsInStock > 0
)
BEGIN
RAISERROR('Cannot reduce stock by more than 50%% at once.',16,1)
ROLLBACK TRAN
END

The trigger fires when an UPDATE is made to Products table. The author states that the Inserted and Deleted tables only exist for the life of the trigger, not before, and not after the trigger runs. If this is true, then why would there be any rows in the Deleted table in this case? No rows were
deleted within the trigger. As far as I can see, no rows have been updated
either. If the condition does exist, no rows will be updated, and an error will be displayed. Otherwise, the row will be updated. Then there would be a row in the inserted table. But then the trigger is finished and the inserted table for that trigger disappears. I think my logic is flawed, which is why I am writing. I don't think I fully understand the Inserted and Deleted tables.

Any help would be greatly appreciated.
Nathan

View 7 Replies View Related

Information_schema.tables, Triggers, Cursors

Jul 8, 2003

how do i return only the tables created by the user?
in three of my databases i am inserting one record per 5 secs. in all the tables. how good is using triggers for 'insert instead of' for these tables?

View 5 Replies View Related

Triggers Affecting Multiple Tables

May 4, 2004

I have a table "PageInfo" wich has columns "PageID, Title(has "AboutUs" as one of the values), DateModified, Active". My other table is "AboutUs" and has columns "ID, WhatsNew, Welcome, Active".

My goal here is that if table "AboutUs" is affected as an "INSERT" or an "UPDATE" on any row, I want "PageInfo.DateModified" WHERE "PageInfo.Title = AboutUs" to be updated with "getDate()". Don't know if I'm clear enough but thanks in advance.

Gazzou

View 7 Replies View Related

Inserting Data Into Tables Having Triggers...

Jul 20, 2005

When you import data using DTS into a table that has triggers - do the triggers fire off if there are triggers for on insert or on after insert?Thanks,--Micah

View 1 Replies View Related

Audit Tables, Delete Triggers, And Asp.net

Jul 20, 2005

i'm in a bit of a bind at work. if anyone could help, i'd greatlyappreciate it.i have a web app connecting to a sql server using sql serverauthentication. let's say, for example, my login/password isdbUser/dbUser. the web app however, is using windows authentication.so if I am logged into the network as 'DOMAINEric', when I access myweb app, my web app knows that I am 'DOMAINEric'. but to the sqlserver db, I am user 'dbUser'.now, i for each table i have, i need to implement an audit table torecord all updates, inserts, deletes that occur against it. i wasgoing to do so with triggers. this is all fine for selects, inserts,and updates. for each table, i have an updatedby and an updatedate.for example, let's say i have a table:create table blah(id int,col1 varchar(10),updatedby varchar(30),updatedate datetime)and corresponding audit table:create audit_blah(id int,blah_id int,blah_col1 varchar(10),blah_updatedby varchar(1),blah_updatedate datetime)for update and insert triggers, i can know what to insert into theupdatedby column of audit_blah because it's in a corresponding row inblah. my web app knows what user is accessing the application, andcan insert that name into blah. blah's trigger will then insert thatname into audit_blah.however, in the case of a delete, i'm not passing in an 'updatedby',because i'm deleting. in this situation, how can the trigger knowwhat user is deleting? the db only knows that sql user 'dbUser' isdeleting, but doesn't know that 'dbUser' is deleting on behalf of'DOMAINEric'. is there any way for my app to inform the trigger toaccess my windows identity without having a corresponding row in thetable from which to pull that info?obviously, i could have each of my app's users log into SQL serverthrough Windows authentication; then i could just use SYSTEM_USER.but let's say, for performance's sake, it'd be better for me to useone sql server login. (i believe one user works better for connectionpooling purposes.) is there a way to get around this?(i'm hoping a built-in function exists that solves all my problems.)suggestions? resources?any help would be great appreciated.happy turkeys.Eric

View 2 Replies View Related

DML Triggers - INSERTED && DELETED Tables

Dec 18, 2007



I'm know the above tables are system generated, am I right in assuming the following.

1) The tables are unique to the current user.

2) The tables only last as long as the transaction that caused their creation

Thanks in advance

Alex

View 1 Replies View Related

Using Triggers To Add Foreign Keys To Child Tables

Apr 29, 2004

I have a situation that I must resolve. I have a program being used by many but I had to create a new table to provide a new feature. The problem I have is this table must use the primary key from the parent table as its primary key, meaning when a user adds a new record to parent table, I need to instantly add the primary key to the child table. Now this was done in the program using sql statements, but I need to implement a trigger or such as to keep me from having to reinstall application on many computers.

basically person inserts new record, then I need to get the new primary ket and add insert it into the child tables. how can I do this with a trigger. I have tried to use an insert into statment with my trigger, but I can't seem to pass the parameters correctly.



CREATE Trigger dbo.Table_Borrower_Insert_Keys
ON Table_Borrower
AFTER INSERT
AS
begin
declare @bid as int

@bid = select MAX(BorrowerID)
FROM Table_SoldProgression

INSERT Table_SoldProgression(BorrowerID)
values (@bid)
end
GO


another attempt

CREATE Trigger dbo.Table_Borrower_Insert_Keys
ON Table_Borrower
AFTER INSERT
AS

INSERT Table_SoldProgression(BorrowerID)
values (select MAX(BorrowerID)FROM Table_Borrower)

GO

View 3 Replies View Related

Triggers - How Do You Join INSERTED Vs DELETED Tables?

Sep 11, 2001

I want to compare the before and after values of an UPDATEd column using a trigger. I want to know if the value in the column has changed. Simple? No!

As you know, SqlServer puts the before image of the UPDATEd rows into the DELETED virtual table and the after image of the UPDATEd rows in the INSERTED virtual table.

So you would get the before and after data by doing a SELECT on these tables.
But here is the problem - how do you join the tables? What if there are >1 rows in these 2 tables (because the UPDATE affected >1 rows) - how do i know which "old"/DELETED rows correspond to which "new"/INSERTED?"
Ok - I could join the 2 tables on the primary key, but what if the primary key was updated? In that case the join would not work - the DELETED table would contain the old primary key value and the INSERTED table would contain the new (different) primary key value. In fact, ALL of the columns may have been changed by the UPDATE.

Now, there is another thing to try with triggers - the
IF UPDATE ( <columname> )
test. This is designed to tell you if a specified column was UPDATEd by the last UPDATE. However, this will return TRUE for any UPDATE that mentions the column - even if the UPDATE does not change any data! So I cannot determine whether a certain column has had its value changed with this either.

So then you can try another test mentioned in the docs for CREATE TRIGGER - the
IF COLUMNS_UPDATED()
test. However, this will report that a column has been updated, NOT whether the data has changed as aresult of that UPDATE.
So if you UPDATE the value in the column to the same value as it was beforehand (admittedly, a pointless thing to do, but it could happen in some apps), this fuction will say, yes, this column was updated.

So my question remains - how do I know if the data has changed in a column after an UPDATE, using a trigger?
Any ideas?

View 1 Replies View Related

Auto Create History Tables And Triggers

May 30, 2007

For my company, we have made it a standard to create history tables and triggers for the majority of our production tables. I recently grew tired of consistently spending the time needed to create these tables and triggers so I invested some time in creating a script that would auto generate these.

We recently launched a project which required nearly 100 history tables & triggers to be created. This would have normally taken a good day or two to complete. However, with this script it took a near 10 seconds. Here are some details about the script.

The code below creates a stored procedure that receives two input parameters (@TableName & @CreateTrigger) and performs the following actions:

1) Queries system tables to retrieve table schema for @TableName parameter

2) Creates a History table ("History_" + @TableName) to mimic the original table, plus includes additional history columns.

3) If @CreateTrigger = 'Y' then it creates an Update/Delete trigger on the @TableName table, which is used to populate the History table.


/************************************************************************************************************
Created By: Bryan Massey
Created On: 3/11/2007
Comments: Stored proc performs the following actions:
1) Queries system tables to retrieve table schema for @TableName parameter
2) Creates a History table ("History_" + @TableName) to mimic the original table, plus include
additional history columns.
3) If @CreateTrigger = 'Y' then it creates an Update/Delete trigger on the @TableName table,
which is used to populate the History table.
******************************************* MODIFICATIONS **************************************************
MM/DD/YYYY - Modified By - Description of Changes
************************************************************************************************************/
CREATE PROCEDURE DBO.History_Bat_AutoGenerateHistoryTableAndTrigger
@TableName VARCHAR(200),
@CreateTrigger CHAR(1) = 'Y' -- optional parameter; defaults to "Y"
AS


DECLARE @SQLTable VARCHAR(8000), @SQLTrigger VARCHAR(8000), @FieldList VARCHAR(6000), @FirstField VARCHAR(200)
DECLARE @TAB CHAR(1), @CRLF CHAR(1), @SQL VARCHAR(1000), @Date VARCHAR(12)

SET @TAB = CHAR(9)
SET @CRLF = CHAR(13) + CHAR(10)
SET @Date = CONVERT(VARCHAR(12), GETDATE(), 101)
SET @FieldList = ''
SET @SQLTable = ''


DECLARE @TableDescr VARCHAR(500), @FieldName VARCHAR(100), @DataType VARCHAR(50)
DECLARE @FieldLength VARCHAR(10), @Precision VARCHAR(10), @Scale VARCHAR(10), @FieldDescr VARCHAR(500), @AllowNulls VARCHAR(1)

DECLARE CurHistoryTable CURSOR FOR

-- query system tables to get table schema
SELECT CONVERT(VARCHAR(500), SP2.value) AS TableDescription,
CONVERT(VARCHAR(100), SC.Name) AS FieldName, CONVERT(VARCHAR(50), ST.Name) AS DataType,
CONVERT(VARCHAR(10),SC.length) AS FieldLength, CONVERT(VARCHAR(10), SC.XPrec) AS FieldPrecision,
CONVERT(VARCHAR(10), SC.XScale) AS FieldScale,
CASE SC.IsNullable WHEN 1 THEN 'Y' ELSE 'N' END AS AllowNulls
FROM SysObjects SO
INNER JOIN SysColumns SC ON SO.ID = SC.ID
INNER JOIN SysTypes ST ON SC.xtype = ST.xtype
LEFT OUTER JOIN SysProperties SP ON SC.ID = SP.ID AND SC.ColID = SP.SmallID
LEFT OUTER JOIN SysProperties SP2 ON SC.ID = SP2.ID AND SP2.SmallID = 0
WHERE SO.xtype = 'u' AND SO.Name = @TableName
ORDER BY SO.[name], SC.ColOrder

OPEN CurHistoryTable

FETCH NEXT FROM CurHistoryTable INTO @TableDescr, @FieldName, @DataType,
@FieldLength, @Precision, @Scale, @AllowNulls

WHILE @@FETCH_STATUS = 0
BEGIN

-- create list of table columns
IF LEN(@FieldList) = 0
BEGIN
SET @FieldList = @FieldName
SET @FirstField = @FieldName
END
ELSE
BEGIN
SET @FieldList = @FieldList + ', ' + @FieldName
END


IF LEN(@SQLTable) = 0
BEGIN
SET @SQLTable = 'CREATE TABLE [DBO].[History_' + @TableName + '] (' + @CRLF
SET @SQLTable = @SQLTable + @TAB + '[History' + @FieldName + '] [INT] IDENTITY(1,1) NOT NULL,' + @CRLF
END


SET @SQLTable = @SQLTable + @TAB + '[' + @FieldName + '] ' + '[' + @DataType + ']'

IF UPPER(@DataType) IN ('CHAR', 'VARCHAR', 'NCHAR', 'NVARCHAR', 'BINARY')
BEGIN
SET @SQLTable = @SQLTable + '(' + @FieldLength + ')'
END
ELSE IF UPPER(@DataType) IN ('DECIMAL', 'NUMERIC')
BEGIN
SET @SQLTable = @SQLTable + '(' + @Precision + ', ' + @Scale + ')'
END


IF @AllowNulls = 'Y'
BEGIN
SET @SQLTable = @SQLTable + ' NULL'
END
ELSE
BEGIN
SET @SQLTable = @SQLTable + ' NOT NULL'
END

SET @SQLTable = @SQLTable + ',' + @CRLF


FETCH NEXT FROM CurHistoryTable INTO @TableDescr, @FieldName, @DataType,
@FieldLength, @Precision, @Scale, @AllowNulls
END

CLOSE CurHistoryTable
DEALLOCATE CurHistoryTable

-- finish history table script with standard history columns
SET @SQLTable = @SQLTable + @TAB + '[HistoryCreatedOn] [DATETIME] NULL,' + @CRLF
SET @SQLTable = @SQLTable + @TAB + '[HistoryCreatedByUserID] [SMALLINT] NULL,' + @CRLF

SET @SQLTable = @SQLTable + @TAB + '[HistoryCreatedByUserName] [VARCHAR](30) NULL,' + @CRLF
SET @SQLTable = @SQLTable + @TAB + '[HistoryAction] [CHAR](1) NOT NULL' + @CRLF
SET @SQLTable = @SQLTable + ' )'


PRINT @SQLTable

-- execute sql script to create history table
EXEC(@SQLTable)

IF @@ERROR <> 0
BEGIN
PRINT '******************** ERROR CREATING HISTORY TABLE FOR TABLE: ' + @TableName + ' **************************************'
RETURN -1
END


IF @CreateTrigger = 'Y'
BEGIN
-- create history trigger
SET @SQLTrigger = '/************************************************************************************************************' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'Created By: ' + SUSER_SNAME() + @CRLF
SET @SQLTrigger = @SQLTrigger + 'Created On: ' + @Date + @CRLF
SET @SQLTrigger = @SQLTrigger + 'Comments: Auto generated trigger' + @CRLF
SET @SQLTrigger = @SQLTrigger + '***********************************************************************************************/' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'CREATE TRIGGER [Trigger_' + @TableName + '_UpdateDelete] ON DBO.' + @TableName + @CRLF
SET @SQLTrigger = @SQLTrigger + 'FOR UPDATE, DELETE' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'AS' + @CRLF + @CRLF
SET @SQLTrigger = @SQLTrigger + 'DECLARE @Action CHAR(1)' + @CRLF + @CRLF
SET @SQLTrigger = @SQLTrigger + 'IF EXISTS (SELECT ' + @FirstField + ' FROM Inserted)' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'BEGIN' + @CRLF
SET @SQLTrigger = @SQLTrigger + @TAB + 'SET @Action = ''U''' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'END' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'ELSE' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'BEGIN' + @CRLF
SET @SQLTrigger = @SQLTrigger + @TAB + 'SET @Action = ''D''' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'END' + @CRLF + @CRLF
SET @SQLTrigger = @SQLTrigger + 'INSERT INTO History_' + @TableName + @CRLF
SET @SQLTrigger = @SQLTrigger + @TAB + '(' + @FieldList + ', HistoryCreatedOn, HistoryCreatedByUserName, HistoryAction)' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'SELECT ' + @FieldList + ', GETDATE(), SUSER_SNAME(), @Action' + @CRLF
SET @SQLTrigger = @SQLTrigger + 'FROM DELETED'


--PRINT @SQLTrigger

-- execute sql script to create update/delete trigger
EXEC(@SQLTrigger)

IF @@ERROR <> 0
BEGIN
PRINT '******************** ERROR CREATING HISTORY TRIGGER FOR TABLE: ' + @TableName + ' **************************************'
RETURN -1
END

END

View 13 Replies View Related

Triggers On Tables Underlying A Partitioned View

Jul 23, 2005

We have a partitioned view with 4 underlying tables. The view and eachof the underlying tables are in seperate databases on the same server.Inserts and deletes on the view work fine. We then add insert anddelete triggers to each of the underlying tables. The triggers modifya different set of tables in the same database as the view (differentthan the underlying table). The problem is those triggers aren't firedwhen inserting or deleteing via the view. Inserting or deleteing theunderlying table directly causes the the triggers to fire, but not whenthe tables are accessed as a result of using the view.Am I missing something? The triggers are 'for insert' and 'fordelete'. No 'instead of' or 'after' triggers.

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved