Cascading Deletes - Which Is Better - A Trigger Or Foreign Key Cascading Delete?
Aug 17, 2005
I need to implement my cascading deletes on a SQL database. Is it better (performance/reliablility-wise) to use the Foreign Key Cascading Deletes or to just write my own triggers to do the deletes?I was hoping someone had experimented and found which works best.
View 2 Replies
ADVERTISEMENT
Nov 13, 2006
I am having great difficulty with cascading deletes, delete triggers and referential integrity.
The database is in First Normal Form.
I have some tables that are child tables with two foreign keyes to two different parent tables, for example:
Table A
/
Table B Table C
/
Table D
So if I try to turn on cascading deletes for A/B, A/C, B/D and C/D relationships, I get an error that I cannot have cascading delete because it would create multiple cascade paths. I do understand why this is happening. If I delete a row in Table A, I want it to delete child rows in Table B and table C, and then child rows in table D as well. But if I delete a row in Table C, I want it to delete child rows in Table D, and if I delete a row in Table B, I want it to also delete child rows in Table D.
SQL sees this as cyclical, because if I delete a row in table A, both table B and table C would try to delete their child rows in table D.
Ok, so I thought, no biggie, I'll just use delete triggers. So I created delete triggers that will delete child rows in table B and table C when deleting a row in table A. Then I created triggers in both Table B and Table C that would delete child rows in Table D.
When I try to delete a row in table A, B or C, I get the error "Delete Statement Conflicted with COLUMN REFERENCE". This does not make sense to me, can anyone explain? I have a trigger in place that should be deleting the child rows before it attempts to delete the parent row...isn't that the whole point of delete triggers?????
This is an example of my delete trigger:
CREATE TRIGGER [DeleteA] ON A
FOR DELETE
AS
Delete from B where MeetingID = ID;
Delete from C where MeetingID = ID;
And then Table B and C both have delete triggers to delete child rows in table D. But it never gets to that point, none of the triggers execute because the above error happens first.
So if I then go into the relationships, and deselect the option for "Enforce relationship for INSERTs and UPDATEs" these triggers all work just fine. Only problem is that now I have no referential integrity and I can simply create unrestrained child rows that do not reference actual foreign keys in the parent table.
So the question is, how do I maintain referential integrity and also have the database delete child rows, keeping in mind that the cascading deletes will not work because of the multiple cascade paths (which are certainly required).
Hope this makes sense...
Thanks,
Josh
View 6 Replies
View Related
Oct 3, 2005
hello guysi am using a table that its secondary key connected to its primary key...and as sql server 2000 doesnt allow cascade delete fore such,i had to write a trigger myselfso i wrote the following triggerCREAT TRIGGER nameON tableFOR DeleteASBEGINIF @@ROWCOUNT >0Delete from table where table.parentID in (select sortID from deleted);ENDthen i went to the table and i tried to delete...and it gave me an error....that there are records that have there parentID= sortID of the table i am trieng to delete...so i deleted the relationship...and kept the triggerand now ...when i delete one...it deletes one level down....but not more....i mean when i delete sortID=4it deletes all the records that has parentID=4...and NOT more..whereas my aim was to have it recursive not to have records lost in my databasehope i explained good as much as i hope to find an answer soon...a clear one...and thanks in advanced...
View 3 Replies
View Related
Dec 21, 1998
I need some suggestions concerning the issue cascading deletes in a self-referencing table, i.e. a table with a foreign key pointing at the primary key in itself. Although SQL Server still does not support cascading deletes the declarative way there are some other ways to handle this situation. One common way is to use trigger coding with the simple structure
CREATE TRIGGER DelCascadeTrig
ON self_ref_tab
FOR DELETE
AS
DECLARE @C_FK xxxxxx
SELECT @C_FK = C_FK FROM DELETED
BEGIN
DELETE self_ref_tab
FROM self_ref_tab, deleted
WHERE self-_ref_tabC_FK = deleted.C_PK
END
where C_PK is the primary key column and C_FK the foreign key column. The problem is that this simple pattern does not work with self-referencing tables, because the removal of dependent rows deeper layer (n-2, n-3 etc. if the originating delete request is level n and the first level of dependant deletes handled by the trigger code is n-1) would require the delete trigger to fire more than once for the same delete operation. As far as I know, in ver. 6.x triggers are executed only once per SQL statement and in this case the n-2, n-3 etc. level rows would have been left as "orphans".
In ver. 7.0 I suppose this should work fine because of the new recursive trigger execution possibility (trigger will fire up to 32 recursive times per SQL statement), but in the meanwhile (i.e. my case util we have upgraded all our servers) the delete logic for a cascading, self-referencing relationship must be handled completely within one execution of the trigger.
My question is now: does anyone know anything about any common algorithm or trigger code example solving this problem.
Thanks in advance
Bjorn Ehnberg
View 1 Replies
View Related
May 24, 2004
When I setup a relationship in Access I can specify that Primary Key deletes cascade down to the Forgien Key. So when I delete an Order Header it cleans up all the items in the Order Details table for me automatically.
Can I get this same functionality in SQL Server 7 without having to write triggers or are triggers the only way?
thanks
dog
View 13 Replies
View Related
Feb 7, 2008
I haven't used cascading deletes in the past but we're starting a new database and it seems like a good way to go to keep data clean. Or at least it did seem like a good way until I ran some tests. I have 3 tables.
People PeopleEmails Email
(pk)peopleid (pk)peopleid (pk)emailid
fname (pk)emailid address
lname emailtype
password
In this structure, the peopleemails table is simply an association table between the email and people table. I have setup up relationships in a diagram so that when a person is deleted, it cascades to peopleemails and removes the entry there. I also had a cascade set up hoping that when an entry was deleted from peopleemails, it would remove it from the email table but this is not happening. The relationship between email and peopleemail is primary key table email.emailid and foreign key table peopleemail.emailid. Is there a way to get this to work to remove the email address if a peopleemail entry is removed? Thanks.
View 5 Replies
View Related
Aug 31, 2006
I have the following tableCREATE TABLE [tbl_Items]([item_id] int IDENTITY(1,1) CONSTRAINT PK_tbl_Items__item_idPRIMARY KEY,[parent_id] int DEFAULT(NULL) CONSTRAINTFK_tbl_Items__item_id__parent_id REFERENCES [tbl_Items]( [item_id] ) ONDELETE NO ACTION ON UPDATE NO ACTION)My Intention was to create a table that when I delete a record, allrecords that have on the [parent_id] field the deleted record[item_id].I am trying to avoid having to use triggers or create a storedprocedure that firsts delete the children (recursively) and thendeletes the parent.Is there any way to do this by changing my table definition here?
View 1 Replies
View Related
Jul 20, 2005
Hi, I'm using SQL server 2000, and I have set up two tables, table Aand table B. Table A and B have a foreign key constraint such that ifan entry is deleted in table A, then all the entries in table Bassociated with that entry are deleted as well. I imagine that I canfind out the number of records that are deleted in table A when Iexecute the SQL, but is there an easy way of determining the number ofrecords that will be deleted in table B?Thanks,Dan
View 1 Replies
View Related
May 19, 2000
Microsoft article Q142480 states "Triggers cannot be used to perform cascading updates and deletes if ForeignKey-to-PrimaryKey relationships have been extablished using SQL Server's DRI."
Does this mean that I cannot declare FK's in my scripts if I want to have triggers in the table? Do I just add a column in my table that will have a foreign key in it, but just not reference it in my script? Can someone clarify for me?
Thanks,
Nathan
View 1 Replies
View Related
Nov 8, 2006
I use SQL Server 2005I have tables tblUserData, tblUsersAndGuestbook, tblGuestbooktblUserdata contains:UserCode intUsername nvarchar(50)tblUsersAndGuestbook contains:Usercode int (FK to tblUserData)GBEntryCode inttblGuestbookGBEntryCode int (FK to tblUsersAndGuestbook)GBText textNow...if I delete a user in tblUserData I want to also delete the entries in tblUsersAndGuestbook AND in tblGuestbook.I've heard something about cascading delete, but how can i configure that in my database?Or do I manually need to delete all entries from code?
View 2 Replies
View Related
Jun 4, 2001
Hi,
I read all the existing material in SWYNK but still am not clear on the following question.
What is the best way to perform Cascading actions (Delete & Update) with foreign Key Constraints declared? We are using SQL Server 7.0
thanks
Rozina
View 1 Replies
View Related
Sep 14, 2004
Procedure spDeleteRows
/*
Recursive row delete procedure.
It deletes all rows in the table specified that conform to the criteria selected,
while also deleting any child/grandchild records and so on. This is designed to do the
same sort of thing as Access's cascade delete function. It first reads the sysforeignkeys
table to find any child tables, then deletes the soon-to-be orphan records from them using
recursive calls to this procedure. Once all child records are gone, the rows are deleted
from the selected table. It is designed at this time to be run at the command line. It could
also be used in code, but the printed output will not be available.
*/
(
@cTableName varchar(50), /* name of the table where rows are to be deleted */
@cCriteria nvarchar(1000), /* criteria used to delete the rows required */
@iRowsAffected int OUTPUT /* number of records affected by the delete */
)
As
set nocount on
declare @cTab varchar(255), /* name of the child table */
@cCol varchar(255), /* name of the linking field on the child table */
@cRefTab varchar(255), /* name of the parent table */
@cRefCol varchar(255), /* name of the linking field in the parent table */
@cFKName varchar(255), /* name of the foreign key */
@cSQL nvarchar(1000), /* query string passed to the sp_ExecuteSQL procedure */
@cChildCriteria nvarchar(1000), /* criteria to be used to delete
records from the child table */
@iChildRows int /* number of rows deleted from the child table */
/* declare the cursor containing the foreign key constraint information */
DECLARE cFKey CURSOR LOCAL FOR
SELECT SO1.name AS Tab,
SC1.name AS Col,
SO2.name AS RefTab,
SC2.name AS RefCol,
FO.name AS FKName
FROM dbo.sysforeignkeys FK
INNER JOIN dbo.syscolumns SC1 ON FK.fkeyid = SC1.id
AND FK.fkey = SC1.colid
INNER JOIN dbo.syscolumns SC2 ON FK.rkeyid = SC2.id
AND FK.rkey = SC2.colid
INNER JOIN dbo.sysobjects SO1 ON FK.fkeyid = SO1.id
INNER JOIN dbo.sysobjects SO2 ON FK.rkeyid = SO2.id
INNER JOIN dbo.sysobjects FO ON FK.constid = FO.id
WHERE SO2.Name = @cTableName
OPEN cFKey
FETCH NEXT FROM cFKey INTO @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
WHILE @@FETCH_STATUS = 0
BEGIN
/* build the criteria to delete rows from the child table. As it uses the
criteria passed to this procedure, it gets progressively larger with
recursive calls */
SET @cChildCriteria = @cCol + ' in (SELECT [' + @cRefCol + '] FROM [' +
@cRefTab +'] WHERE ' + @cCriteria + ')'
print 'Deleting records from table ' + @cTab
/* call this procedure to delete the child rows */
EXEC spDeleteRows @cTab, @cChildCriteria, @iChildRows OUTPUT
FETCH NEXT FROM cFKey INTO @cTab, @cCol, @cRefTab, @cRefCol, @cFKName
END
Close cFKey
DeAllocate cFKey
/* finally delete the rows from this table and display the rows affected */
SET @cSQL = 'DELETE FROM [' + @cTableName + '] WHERE ' + @cCriteria
print @cSQL
EXEC sp_ExecuteSQL @cSQL
print 'Deleted ' + CONVERT(varchar, @@ROWCOUNT) + ' records from table ' + @cTableName
--------
The above code is good .. but has limitation...throws an error:
Server: Msg 217, Level 16, State 1, Procedure spDeleteRows, Line 58
Maximum stored procedure, function, trigger, or view nesting level exceeded (limit 32).
Can anyone out there suggest a better way of implementing on a database without a limitation of levels.. we are talking about a HUGE DB with lots of table and FK referentials..
Please advice.. or solve the problem..
Thank you
View 2 Replies
View Related
Jul 20, 2005
I use cascading delete on my SQL Server Database. I am experiencing along query time on my highest level delete, 10 minutes. If I deletefrom each table manually and then delete the parent, I will usually bedone in less than a minute. Any suggestions?
View 1 Replies
View Related
Aug 18, 2007
If we want to maintain the data in relationships.
There are two ways to do it.
1. Auto (Like Cascading Update And Delete)
2. Manually (Like In Stored Procedures)
I read an intresting article
http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=419
In this article Imar has choosen the second way (Manually).
And when I talk to Imar.
He said, "Cascading deletes would have worked equally well in this situation. However, I personally don't like them too much. I am much rather in control, enabling me to delete what I want and when I want it. I could, for example, keep certain data for "time travelling scenarios" (e.g. the state things were in some time ago) or I might want to keep it for other purposes."
Can any one help me to choose the better one.
Waiting for helpful replies.
View 2 Replies
View Related
Nov 3, 2000
Can someone pls help me with a syntax example of a cascading delete trigger.
thanks
View 2 Replies
View Related
Jul 15, 1999
Is it possible to perform a cascading delete and update using TRIGGERS on a table referenced by a foreign key constraint.?To be more specific.. if the primary key is deleted does the delete trigger on the primary table deletes the record in the foreign key table or does it return an error??
if possible please send us the T SQL Statements .
Thanks in Advance
Geenu
Ajaz Dawre
View 2 Replies
View Related
Nov 16, 2006
Edit: Sorry This is OSQL.What I use as my query is:"DELETE FROM timerecord WHERE Actual_Time_In LIKE '11.12.2006%'"The row of Actual_Time_In is formatted with Date and time (MM.DD.YYYY HH:MM:SS) sometimes there are ten records and I'd rather not have to remove them from the table one at a time. However, even though I have a record that is '11.12.2006 22:43:00' my delete doesn't work osql states I have 0 rows affected.This is only MSDE so I don't have anyother way to open the table.Sometimes these records have other records that reference them. Is there anyway to do a cascading delete without it getting to complex?Thanks of all your help, I am just a tech support guy beating his head against a wall..
View 2 Replies
View Related
Sep 14, 2007
I was hoping someone could explain how cascading deletes work in Peer to Peer replication on SQL 2005 SP2, the child tables are also being replicated.
View 1 Replies
View Related
Feb 16, 2008
This function will generate all DELETE statements in correct order to perform a CASCADING delete.
For self-joined tables, it will generate the T-SQL code to "unwind" the table, also in correct order!CREATE FUNCTION dbo.fnCascadingDelete
(
@Schema NVARCHAR(128) = NULL,
@Table NVARCHAR(128) = NULL
)
RETURNS@Return TABLE
(
RowID INT PRIMARY KEY CLUSTERED,
IsSelfJoin TINYINT NOT NULL,
HasPk TINYINT NOT NULL,
[SQL] NVARCHAR(4000) NOT NULL
)
AS
BEGIN
DECLARE@Constraints TABLE
(
RowID INT NOT NULL,
Indent SMALLINT NOT NULL,
[Catalog] NVARCHAR(128) NOT NULL,
[Schema] NVARCHAR(128) NOT NULL,
[Table] NVARCHAR(128) NOT NULL,
[Column] NVARCHAR(128),
pkCatalog NVARCHAR(128),
pkSchema NVARCHAR(128),
pkTable NVARCHAR(128),
pkColumn NVARCHAR(128),
pkType NVARCHAR(128),
pkSize INT,
IsSelfJoin TINYINT NOT NULL,
HasPk TINYINT NOT NULL
)
INSERT@Constraints
(
RowID,
Indent,
[Catalog],
[Schema],
[Table],
[Column],
pkCatalog,
pkSchema,
pkTable,
pkColumn,
pkType,
pkSize,
IsSelfJoin,
HasPk
)
SELECTRowID,
Indent,
[Catalog],
[Schema],
[Table],
[Column],
pkCatalog,
pkSchema,
pkTable,
pkColumn,
pkType,
pkSize,
SelfJoin,
CASE
WHEN [Column] IS NULL THEN 0
ELSE 1
END
FROMdbo.fnTableTree(@Schema, @Table)
IF @@ROWCOUNT = 0
RETURN
DECLARE@SQL TABLE
(
ID INT IDENTITY(1, 1),
RowID INT PRIMARY KEY CLUSTERED,
IsSelfJoin TINYINT NOT NULL,
HasPk TINYINT NOT NULL,
[SQL] NVARCHAR(4000) NOT NULL
)
DECLARE@Indent SMALLINT,
@RowID INT,
@ID INT,
@TSQL NVARCHAR(4000),
@RowSQL NVARCHAR(4000),
@EndSQL NVARCHAR(4000),
@pkColumn NVARCHAR(128),
@IsSelfJoin TINYINT,
@HasPk TINYINT
DECLARE@Unwind TABLE
(
RowID INT NOT NULL,
StepID INT IDENTITY(0, 1) PRIMARY KEY NONCLUSTERED,
[SQL] NVARCHAR(4000)
)
WHILE NOT EXISTS (SELECT * FROM @SQL WHERE RowID = 1)
BEGIN
SELECT TOP 1@RowID = c.RowID,
@ID = c.RowID,
@Indent = c.Indent,
@TSQL = N'',
@EndSQL = N'',
@IsSelfJoin = c.IsSelfjoin,
@HasPk = c.HasPk
FROM@Constraints AS c
LEFT JOIN@SQL AS s ON s.RowID = c.RowID
WHEREs.RowID IS NULL
ORDER BYc.Indent DESC,
c.RowID DESC
WHILE @ID > 0
BEGIN
IF @Indent = 0
SELECT@RowSQL = N'DELETE t' + CAST(@RowID AS NVARCHAR(12)),
@RowSQL = @RowSQL + N' FROM ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]) + N' AS t' + CAST(@ID AS NVARCHAR(12)),
@EndSQL = N' WHERE t' + CAST(@ID AS NVARCHAR(12)) + '.' + QUOTENAME(COALESCE(c.[Column], '%0')) + N' = ''%1''',
@IsSelfJoin = @IsSelfJoin | c.IsSelfJoin
FROM@Constraints AS c
WHEREc.RowID = @ID
ELSE
SELECT@RowSQL = N' INNER JOIN ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]),
@RowSQL = @RowSQL + N' AS t' + CAST(@ID AS NVARCHAR(12)) + N' ON t' + CAST(@ID AS NVARCHAR(12)) + N'.' + QUOTENAME(c.[Column]),
@pkColumn = QUOTENAME(c.pkColumn),
@IsSelfJoin = @IsSelfJoin | c.IsSelfJoin
FROM@Constraints AS c
WHEREc.RowID = @ID
SELECT TOP 1@ID = c.RowID,
@Indent = c.Indent,
@RowSQL = @RowSQL + N' = t' + CAST(c.RowID AS NVARCHAR(12)) + N'.' + @pkColumn,
@IsSelfJoin = @IsSelfJoin | c.IsSelfJoin
FROM@Constraints AS c
WHEREc.RowID < @ID
AND c.Indent < @Indent
ORDER BYc.Indent DESC,
c.RowID DESC
IF @@ROWCOUNT = 0
SET@ID = 0
SET@TSQL = @RowSQL + @TSQL
END
INSERT@SQL
(
RowID,
IsSelfJoin,
HasPk,
[SQL]
)
VALUES(
@RowID,
@IsSelfJoin,
@HasPk,
@TSQL + @EndSQL
)
IF @IsSelfJoin = 1
BEGIN
DECLARE@Yak NVARCHAR(160),
@Catalog NVARCHAR(128),
@Column NVARCHAR(128)
SELECT@Yak = pkType + COALESCE('(' + CAST(pkSize AS NVARCHAR(12)) + ')', ''),
@Catalog = [Catalog],
@Schema = [Schema],
@Table = [Table],
@Column = [Column],
@Catalog = [Catalog],
@Table = [Table],
@pkColumn = pkColumn
FROM@Constraints
WHERERowID = @RowID
SET@RowSQL = 'DECLARE@Lvl INT
SET@Lvl = 0
DECLARE@Stage TABLE (RowID INT IDENTITY(0, 1), Lvl INT, RowKey ' + @Yak + ')
INSERT @Stage (Lvl, RowKey) '
+ REPLACE(@TSQL + @EndSQL, 'DELETE t' + CAST(@RowID AS NVARCHAR(12)) + '', 'SELECT 0, t' + CAST(@RowID AS NVARCHAR(12)) + '.' + QUOTENAME(@Column) + '')
+ ' WHILE @@ROWCOUNT > 0
BEGIN
SET@Lvl = @Lvl + 1
INSERT@Stage (Lvl, RowKey)
SELECT@Lvl,
t.' + QUOTENAME(@pkColumn) + '
FROM' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' AS t
INNER JOIN@Stage AS s ON s.RowKey = t.' + QUOTENAME(@Column) + '
AND s.Lvl = @Lvl - 1
LEFT JOIN@Stage AS cr ON cr.RowKey = t.' + QUOTENAME(@pkColumn) + '
WHEREcr.RowKey IS NULL
END
SELECT ''DELETE FROM ' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' WHERE ' + QUOTENAME(@pkColumn) + ' = '' + QUOTENAME(RowKey, '''''''')
FROM @Stage
WHERE RowID > 0
ORDER BY RowID DESC'
INSERT@Unwind
(
RowID,
[SQL]
)
VALUES(
@RowID,
@RowSQL
)
END
END
INSERT@Return
(
RowID,
IsSelfJoin,
HasPk,
[SQL]
)
SELECTs.ID,
s.IsSelfJoin,
s.HasPk,
CASE
WHEN u.RowID IS NULL THEN s.[SQL]
ELSE u.[SQL]
END
FROM@SQL AS s
LEFT JOIN@Unwind AS u ON u.RowID = s.RowID
ORDER BYs.ID,
u.StepID
RETURN
ENDE 12°55'05.25"
N 56°04'39.16"
View 16 Replies
View Related
Aug 4, 2015
I have a table which has a recursive relationship to its self neither of the columns involved are FK columns
CREATE TABLE [dbo].[ix_Trace](
[Trace_Id] [uniqueidentifier] NOT NULL,
[Trace_BubbledTraceEnter_Id] [uniqueidentifier] NULL,
[Trace_EnterId] [uniqueidentifier] NULL,
[Trace_Application_Id] [uniqueidentifier] NULL,
[Trace_Session_Id] [uniqueidentifier] NULL,
....
Where Trace_EnterId is the parent ID and BubbledTraceEnter_Id is the child ID. My test case has nested trace lines that go down 5 levels, but when I delete the top trace line, only the child directly under it is deleted leaving the other 3 as orphans. Here's the trigger:
ALTER TRIGGER [dbo].[DTrig_xTrace]
ON [dbo].[ix_Trace]
FOR Delete
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM ix_Trace
FROM ix_Trace INNER JOIN
deleted as dt ON ix_Trace.Trace_BubbledTraceEnter_Id = dt.Trace_EnterId
How can I make this cascade all the way down?
View 7 Replies
View Related
Dec 15, 2005
Hi
I have three params p1 , p2 and p3.
All 3 are non queried with values Yes and NO .
if p1 is yes only i have to enable the remaining twp params otherwise disable them.
Can some one suggest as to how this can be achieved.
Thanks
View 1 Replies
View Related
Jun 30, 2005
This question is for Bill directly. Hi Bill, I have lots of experience with RS, implementing the beta in a production environment, I was so impressed. Currently my company uses Cognos for financial reporting, and I am hoping to replace this with RS and MSAS. I have little knowledge of MDX, so I have been using your various series of articles to get up to speed. However, I don't get the article Mastering OLAP Reporting: Cascading Prompts. I fully understand how to build the prompts, but there seems to be a step missing in the article. You never replace the hardcoded where clause in the base dataset, and I can't seem to work out how to pass the parameter from the cascading prompts to the report. Maybe I'm being stupid, but the article doesn't seem to tell us how to do that.
Many Thanks
Sam
View 3 Replies
View Related
Mar 28, 2006
Hi All
I am using RS 2000. I used 2 input parameters for one of the report. The 2nd parameter is based on the 1st parameter. i.e. First Parameter is Country and 2nd Parameter is State. Based on the Country selection the list of states for the selected country will get displayed. This is working fine in Reporting services as well as report server. When deploying into the application it doesn't work.
If you have solution for this I would like to share.
Regards
Venkataraman M
ramanmahalingam@hotmail.com
View 6 Replies
View Related
Aug 5, 2004
Here's my table setup:
tblSteps:
StepID int IDENTITY
ParentStepID int ALLOWSNULLS
OtherID int
Amount money
tblOther:
OtherID int IDENTITY
Amount money
Now, I have a trigger defined on tblSteps:
Code:
CREATE TRIGGER tgrUpdateAmount
ON dbo.tblSteps
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
DECLARE @Amount money
SET @Amount = ISNULL((SELECT SUM([Amount]) FROM inserted), 0) - ISNULL((SELECT SUM([Amount]) FROM deleted), 0)
IF (SELECT [ParentStepID] FROM inserted) IS NULL
BEGIN
UPDATE tblOther SET [Amount] = [Amount] + @Amount WHERE [OtherID] = (SELECT [OtherID] FROM inserted)
END
ELSE
BEGIN
UPDATE tblSteps SET [Amount] = [Amount] + @Amount WHERE [StepID] = (SELECT [ParentStepID] FROM inserted)
END
END
What this code basically does is this: if you update the amount of a Step that has a ParentStepID, it will take what was addded (or deleted etc...) and update it's parent with the added amount. If the Step does not have a ParentStepID, it will take the amount add add it to the Other row it corresponds to.
Here's an example of some test data:
tblOther:
OtherID: 1
Amount: 0
tblSteps:
StepID: 1
ParentStepID: NULL
Amount: 0
------
StepID: 2
ParentSTepID: 1
Amount: 0
If I update the Amount to 100 for StepID=2, it also updates the amount for StepID=1. If I update the amount for StepID=1, it also updates the amount for OtherID=1. However, when I update the amount for StepID=2, it does not cascade up to the tblOther level (e.g. Updating StepID=2 should update StepID=1 which should update OtherID=1, right?)
Basically, the trigger isn't cascading. Can anyone point out what I need to do?
Thanks
View 1 Replies
View Related
Apr 15, 2008
Hi
I am doing report development against cube (OLAP) and I have several parameters. My second parameter is to be filtered based on the first parameter (kinda like cascading), but how do we achieve this in a cube environment? Lets say I have param1 and param2 in a dataset. I want Param2 to show the locations only based on what I select in Param1. Hope this helps. If you have questions, please let me know.
View 1 Replies
View Related
Mar 21, 2007
hi all,
In my report I want to make certain parameters to depend on the previous parameters. I think we can use those as cascading parameters. How to make a parameter a cascading parameter? and how to use those cascading parameter ? It would be nice of you if you can help me.
Thanking you,
Lekshmi
View 4 Replies
View Related
Jul 20, 2005
We have a situation that occurs every so often with blocking ofvarious databases on one server (Win200 SQL7). It appears to happen atrandom, so I'm assuming it originates from something a user does andnot a regularily run process.We've examined the data available to us and used the very helpfulblocking code on http://www.algonet.se/~sommar/sqlutil/aba_lockinfo.html(Thanks Erland).Were getting closer to finding the problem, but need some advice onwhat to look for.This is a bit of guesswork, but we suspect that we get into asituation where blocking takes places, and this then cascades to otherprocesses which then block others in turn. The original culprit thenfinishes, but the blocks continue as the newer processes are holdingsomething else up. A bit like dominoes. It seems to take a while tofree this up.The problem we have is determining the start of this process. Once weare made aware of blocking issues, we can find out who is doing what,but almost always get a different answer/user and think we're gettingto it a little late.Ideally, I want to log the blocking somewhere so I can examine thefiles when this occurs and can therefore establish a pattern etc...Any ideas or suggestions would be welcome.
View 1 Replies
View Related
Jun 1, 2007
I have a report that is based on 2 listboxes, the second one's values dependent on the value selected in the first box. How would I display all values in both list boxes on the report if I so decided?
Thanks,
The Rook
View 3 Replies
View Related
Sep 24, 2007
I have 2 parameters that are of type string. The user can enter anything they want in them. The third parameter is query based and uses the first 2 parameters to get a list of people. Is there a way I can prevent the third parameter from propigating until the first 2 are both filled in? The first 2 cannot be drop downs however, they are used in a wild card fashion.
Thanks!
View 6 Replies
View Related
Apr 25, 2007
Hi,
I have a listbox which selects distinct brands from the products table.
Then another list box which lists all the orders with order description. Each order has a unique system generated ORDERID and the user provides the orderdescription which could be duplicate.
Depending on the Brand selected by the user in the earlier list box, only those orders containing the the brands in order details files should be available for selection in the list box.
e.g. BRands Lisbox shows: Cream A, Cream B and Cream C
If the user selects 'Cream A', then the next list box shows orderdescription as 'Cream A order for regular sale','Cream A order for exhinition sale', 'Cream A order for exhibition sale'
The problem here is that if the user selects a description which is duplicate (could be the case), then the system brings back the wrong order details.
How is it possible to allow a user to select a order description but search on the OrderID?
Thanks for the help
regards
josh
View 1 Replies
View Related
Mar 20, 2007
Hi,
I am using SQL Server 2005 reporting services. I am having a problem with Cascading Parameters. In my report there are 4 parameter . (Product Class, Product Type, Product SubType and Activites). when user open the report page he/she will have to select a value for product class depending on the selection Product Type and Sub type will be populated. So far its good, but Activities also depends on the Product Class. My question is can we have 2 parameters depend on same parameter. Here in this case Product Type and Activities both depend on the Product Class. I want only those activies in the dropdown which belongs to the Product Class that is selected.
Can anyone please give an ideas?
Thanks
Ashwini
View 10 Replies
View Related
May 21, 2008
I need to "cascade clone" or "cascade copy" one row only, in a given database table, but I also need to copy all the child records in related tables, yet preserving the Primary-Foreign key relationships.
Say I have 3 DB Tables.Companies with a key named CompanyID.Employees with a key named EmployeeID and a FK to CompanyID.Projects with a Foreign Key to EmployeeID
One company may contain several employees, and each employee may have several projects.(See this image for reference www.AgustinGarzon.com/3RelatedTables.jpg )
I need you to point me to a procedure that enables me to copy, for example, one Company record, and have all the associated Employees copied over, and for each Employee, have all the Projects associated copied over.
This is what I call a "Cascade copy", because it's a process that walks down all the database structure, starting from a given field, and looking down through all the database relational hierarchy.
There might be a straight way I can accomplish this task, although I'm unable to find it.I could write a .net script where I specify the Table Names, the Prikmary Keyname and the Foreign Keyname, but this doesn't sound like a clean solution.
The most important thing is keep a correct Foreign to Primary relationship once the fields have been copied. I mean, if we clone a company:
1- All the employees should be also copied.2- All the new employees should relate to the new company primary key.3- All the projects should be also copied.4- All the projects should related to the new employee primary key.
I'm attaching an image so you can easily see the pretty simple database structure I'm talking about.www.AgustinGarzon.com/3RelatedTables.jpg
I'm also attaching the VS2005 project with the SQL Express database.www.AgustinGarzon.com/TestSolution.zip
Look forward to receiving some tips and links to resources so I can achieve this task, preferably through a SQL stored procedure or an ASP.NET script.
Best Regards.
Agustin Garzon
View 2 Replies
View Related
Jan 27, 2004
I may have misinterpreted the error I just got...but.. is it impossible in SQL Server to have a cascade delete FK constraint that leads to a table which has another cascade delete FK?? What's a workaround? Triggers?
View 5 Replies
View Related