How To Use Triggers To Enforce Cross-database Referential Integrity?
Aug 1, 2001Can someone give me an example on how to enforce cross-database referential integrity with triggers in SQL Server 2000?
Thanks,
Joel
Can someone give me an example on how to enforce cross-database referential integrity with triggers in SQL Server 2000?
Thanks,
Joel
Using the new referential integrity constraints that will be made available, will it allow us to manually define the relationships between entities even if there is no true foreign key constraints setup in the database?
Lets say we deleted the FK_Orders_Customers in Northwind between orders and customers.
Or is this ability available now?
Thank for your time.
Is there a way to disable referential integrity on all destination tables for an import?
Thanks.
In SQL Server 2012 (also 2005 and 2008), can you have Referential Integrity across a Database? Across a Schema?
View 1 Replies View RelatedUsing SQL Server 2005, I have two databases.
AppDB - The main application database.
GeoDB - A somewhat static ZIP code / states / other geographic stuff database
I need to have some foreign key columns in tables in AppDB reference columns in the GeoDB database tables. Eventually other application database besides AppDB will be doing the same thing in our infrastructure. After googling and reading for days, here is what I think I know:
You cannot create foreign keys that reference tables in another database in SQL Server.
You cannot create foreign keys that reference columns in a view, and you definitely cannot make an index on a view that has base tables in another database.
You can create a trigger that references tables in another database, but this can be flaky? (nested/recursive trigger problem).
SQLServer2005 supports multiple schemas within the same database. Maybe I should logically separate my databases this way? Seems like it would be a tough solution to manage since I already have some databases live in production that will eventually use this 'static' GeoDB. Also, seems like itwouldn't be as portable as keeping the GeoDB info in its own database, but maybe I'm being too software engineer-ish here - afraid of low cohesion, high coupling.
I will greatly appreciate any advice I can get, any links to articles, or any more options I am missing.
Thanks,Adam Nofsinger
ucnmedia.com
I've got a table that includes:CREATE TABLE [dbo].[Content] ( [Id] int IDENTITY(1, 1) NOT NULL, [ParentId] int NULL,
I'm wanting to make sure that a ParentId must be in the table as Id someplace else. When I try to do it by making it a foreign key get the error:
--------------- SQL ---------------
ALTER TABLE [dbo].[Content]ADD CONSTRAINT [Content_fk3] FOREIGN KEY ([Id]) REFERENCES [dbo].[Content] ([ParentId]) ON UPDATE NO ACTION ON DELETE NO ACTIONGO
---------- ERROR MESSAGE ----------
There are no primary or candidate keys in the referenced table 'dbo.Content' that match the referencing column list in the foreign key 'Content_fk3'.Could not create constraint. See previous errors.
Any ideas?
ALTER TABLE [dbo].[Content]ADD CONSTRAINT [Content_fk3] FOREIGN KEY ([Id]) REFERENCES [Content].[dbo] ([ParentId]) ON UPDATE NO ACTION ON DELETE NO ACTIONGO
Hi,I have two tables Table A and B, below with some dummy data...Table A (contains specific unique settings that can be requested)Id, SettingName1, weight2, lengthTable B (contains the setting values, here 3 values relate to weightand 1 to length)Id, Brand, SettingValue1, A, 1001, B, 2001, null, 3002, null, 5.3(There is also a list of Brands available in another table). No primarykeys / referential integrity has been setup yet.Basically depending upon the Brand requested a different setting valuewill be present. If a particular brand is not present (signified by anull in the Brand column in table B), then a default value will beused.Therefore if I request the weight and pass through a Brand of A, I willget 100If I request the weight but do not pass through a brand (i.e. null) Iwill get 300.My question is, what kind of integrity can I apply to avoid the userspecifying duplicate Ids and Brands in table B. I cannot apply acomposite key on these two fields as a null is present. Table B willprobably contain about 50 rows and probably 10 of them will be brandspecific. The reason its done like this is in the calling client code Iwant to call some function e.g.getsetting(weight) .... result = 300Or if it is brand specificgetsetting(weight,A) ..... result = 100Any advice on integrity or table restructuring would be greatlyappreciated. Its sql 2000 sp3.Thanksbrad
View 9 Replies View RelatedUsing SQL Server Express 2005, I have two databases. AppDB - The main application database.GeoDB - A somewhat static ZIP code / states / other geographic stuff databaseI need to have some foreign key columns in tables in AppDB reference columns in the GeoDB database tables. Eventually other application database besides AppDB will be doing the same thing in our infrastructure. After googling and reading for days, here is what I
think I know:You cannot create foreign keys that reference tables in another database in SQL Server.You
cannot create foreign keys that reference columns in a view, and you definitely cannot make an index on a view that has base tables in another database.You can create a trigger that references tables in another database, but this can be flaky? (nested/recursive trigger problem).SQLServer
2005 supports multiple schemas within the same database. Maybe I should logically separate my databases this way? Seems like it would be a tough solution to manage since I already have some databases live in production that will eventually use this 'static' GeoDB. Also, seems like it
wouldn't be as portable as keeping the GeoDB info in its own database,
but maybe I'm being too software engineer-ish here - afraid of low
cohesion, high coupling.I will greatly appreciate any advice I can get, or any more options I am missing. Thanks,Adam Nofsingerucnmedia.com
Hi,
We are in search of beta testers for our new software tool for SQL Server : Remote Keys allows you to define and enforce cross databases integrity constraint. With Remote Keys, you can create a foreign key between to SQL tables located in distinct databases.
Beta version can be downloaded here : www.remote-keys.com.
Thank you,
Tom
Hi,
We are in search of beta testers for our new software tool for SQL Server :
Remote Keys allows you to define and enforce cross databases integrity
constraint. With Remote Keys, you can create a foreign key between to SQL
tables located in distinct databases.
New version (beta 2) can be downloaded here : http://www.remote-keys.com
Thank you,
Tom
Question:
What is used to enforce referential integrity ?
Answer: Triggers; Foriegn Keys.
what is Foreign Keys ?
How do you enforce referential integrity in SQL between tables?
Thanks.
I used to work with little databases and throw everything into a table with no relation, and modify them all individually. Now I've learned about referential integrity, makes things a lot easier.
My question is, now what? Say I have a Customers table and an Orders table (to keep it simple). If custID is the primary key in customers, foreign key in orders, then if I want to insert into Orders, I need the custID. So those kinds of things I need to keep stored in a session state and insert them like that, correct?
Hi guys,
Is there a way of finding the foreign keys for a table and therefore determine weather any referential integrity rules would be broken if a record was deleted?
For example. You have an author you want to delete, but that author has books. You call a procedure to delete the author. The stored procedure checks the foriegn keys, checks the tables and determines what is in them and if any tables have records that would be "orphaned" you return an error reporting what tables have the "would be orphaned" data in them.
It need to be fairly generic int he manner that it checks the foreign keys and the sub table data.
This is on behalf of a guy at work so "requirements" may change. ;)
Anyone got some ideas??
Cheers,
Shaun
hi guys,
i was asked to drop some tables...but before dropping i was asked to check for referential integrity..
so where and how can i check this referential integrity????
Hihow to set the referential integrity between 2 tables using enterprisemanager (microsoft SQL SERVER).. i tried and the tab doesn't allow meto choose. pls.help.thankssree--chavasreedharMessage posted via http://www.exforsys.com for all your training needs.
View 1 Replies View RelatedI'm not sure about the way you enforce the referential integrity in a SQL server 6.5 database (I'm new to this environment). Does any one have an exemple. The doc I have is useless...Thanks
View 1 Replies View RelatedWhat ate the method/techniques i can use for enforcing referential integrity, Without using foreign key constraints ?
View 7 Replies View RelatedI'm using Microsoft SQL Server Management Studio Express 9.00.2047.00and expriencing problems with setting referential integrity on a linktable. The tables' schema is as follows:-------------------------------------------------------------------CREATE TABLE competencies (CID bigint identity(1,1) CONSTRAINT pk_CID PRIMARY KEY,LockedBy bigint DEFAULT 0 NOT NULLCONSTRAINT fk_UserIDREFERENCES usr_info(userID)ON DELETE SET DEFAULTON UPDATE CASCADE)---------------------------------------------------------CREATE TABLE usr_info (userID bigint IDENTITY(0,1) CONSTRAINT pk_UID PRIMARY KEY,ActiveFlag bit default 0 NOT NULL, --(1='Yes', 0='No')FirstName varchar(100) default '' NOT NULL,LastName varchar(100) default '' NOT NULL)-------------------------------------------------------CREATE TABLE competency_hdr (fkCID bigint default 0 NOT NULLCONSTRAINT fkCID_chREFERENCES competencies(CID)ON DELETE CASCADEON UPDATE CASCADE,ApprovedBy bigint default 0 NOT NULLCONSTRAINT fkUserID_chREFERENCES usr_info(userID)ON DELETE SET DEFAULT -- NO delete if user is deletedON UPDATE CASCADE)--------------------------------------------------------When I execute the above I get the following error message.Msg 1785, Level 16, State 0, Line 1Introducing FOREIGN KEY constraint 'fkUserID_ch' on table'competency_hdr' may cause cycles or multiple cascade paths. SpecifyON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGNKEY constraints.Msg 1750, Level 16, State 0, Line 1Could not create constraint. See previous errors.Now, if i swap the fields around then the error message changes tothat of the fkCID field.Basically what I want is:when I delete a competency record I need all references to this recordto be deleted.when I delete a user I want to set the foreign key to zero (the recordmust remain on the database).Obviously there is something I'm missing here. Any advice, anyone?---------------------------------------------------------------Join Bytes! : Remove your pants to reply---------------------------------------------------------------
View 6 Replies View RelatedHow I do, in SQL SERVER 7.0, referential integrity (Foreign Key constraints) between tables storaged in differents databases?.
Thank for any help.
Hi,
I need to write a referential integrity trigger. I have two tables called Table1 and Table2. In both the tables i have common column called FieldA.
Now i need to write a trigger, whenever i updates Table1 this trigger automatically needs to update a FieldA in Table2.
Can anyone give me Code or suggestions , how to write this trigger. I am new to triggers.
Thank you!
---Ram
Hi,
I need to write a referential integrity trigger. I have two tables called Table1 and Table2. In both the tables i have common column called FieldA.
Now i need to write a trigger, whenever i updates Table1 this trigger automatically needs to update a FieldA in Table2.
Can anyone give me Code or suggestions , how to write this trigger. I am new to triggers.
Thank you!
I know how to write a normal insert , update, delete triggers and using help from books online.. SO pls do it in useful.
---Ram
Hi All,
I am inserting into a table that hold several foreign keys from several tables.
I'm performing this via a client (VB) and I only how to capture the error, but unable to determine which column/field is the one that violates referential integrity.
Any one can shed some light here? Many thanks!
Cyherus
I have a lookup table called States, I have multiple other tables that use this lookup table, but I can only relate to one other table. My question is if I change a state name how do I enforce that change to the other tables that CANT be related? I know it is a design flaw and need some kind of joining table. I am having difficulty understanding and incorporating first normal form in my database. Here is what i have so far.
Example:
Table 1
========|============|=============|========|
CustomerID BillingAddressID ShippingAddressID OtherFields
========|============|=============|========|
Table 2
===========|======|========|
BillingAddressID StateID OtherFields
===========|======|========|
Table 3
=============|======|========|
ShippingAddressID StateID OtherFields
=============|======|========|
Table 4
======|====|
StateID Name
======|====|
How do I relate table 4 with table 2 & 3 for referential integrity? Or create a joiner table?
hi there!
im having problems deleting rows in a reference table. is there any tools which tables to delete first before deleting the rows in the table which contains the primary key?
i have a lot of tables let say over 300 so its hard for me to guess which comes first... what should i keep in mind deleting rows with a referential integrity?
thank...
Two ways to do this... Creating the constraints when creating the data model OR using SQL to use the 'reference' constraint. Does 2005 provide any other automated method of creating the Primary Key - to Foreign key constraints without writing the SQL to do this?
Thx
Hello Everyone.
I'm trying to set a procedural referential integrity on a table, files, which references to table users (a file is created by a user but one user can have more than one file).
Here, given that I can't create a referential integrity ON DELETE SET NULL (the reason il long to explain so just don't care about it), I would like to emulate the RI with a trigger.
On deleting a user the files associated to him have their IDUser set to null.
I have a problem, this is the trigger:
CREATE TRIGGER PRI_FilesOnUsers
ON Files
INSTEAD OF DELETE
AS
-- When a user is deleted the files must have no user associated, set IDUser to null
UPDATE Files
SET IDUser = NULL
WHERE IDUser = ?????????????????????????????????????????????????????
GO
WELL what do I heve to put there, how can i retrieve the values of the fields of the record that the user tried to delete?????Help me thanks
Hi,
How could I define referential integrity using FK constraint which allow me to have empty string/ZERO number instead of NULL value ?
Thank you
I'm designing a database to store information about jobs that are in progress at a property. More than one job can be in progress at a property at one time and each different kind of job can contain different data, although they all share some common fields such as StartDate.
So I have a table that stores the property details PropertyDetails:
*ID
PropertyAddress
PropertyPostCode
Then I have a table that stores all of the jobs' shared details:
*PropertyID
*JobID - These three make up a compound primary key
*JobType
StartDate
EndDate
Then I have individual tables for each of the Jobs, for example BuildingWork:
*JobID
BuildingContractor
InsuranceCompany
Which works great, and enables me to query all basic job details from one table (JobDetails) rather than multiple tables for every job type.
BUT: I don't know how to enforce the referential integrity of the database. Obviously I can use a constraint to cascade deletes from the PropertyDetails table to the JobDetails table through the PropertyID, but there doesn't appear to then cascade the deletes from the JobDetails table to the individual Job tables as JobDetails has no idea what tables are there.
If I store the relevant individual table name as the JobType in the JobDetails table, could I use a trigger to somehow delete the related record from that table?
Littlecharva
I have transaction table where the rows entered into the transactioncan come a result of changes that take place if four different tables.So the situation is as follows:Transaction Table-TranId-Calc AmountTable 1 (the amount is inserted into the transaction table)- Tb1Id- Tb1AmtTable 2 (an amount is calculated based on the percentage and insertedinto the transaction table)-Tbl2Id-Tb2PercentageTable 3 (the amount is inserted into the transaction table)-Tbl3Id-Tbl3AmutTable 4 (an amount is calculated based on the percentage and insertedinto the transaction table. )-Tbl2Id-Tb2PercentageHow do I create referential integrity between the Transaction table andthe rest of the tables. When I make changes to the values in Table 1 -4, I need to be able to reflect this in the Transaction table.Thanks.
View 6 Replies View RelatedI 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
Hello every body,I need some clarification of concept regarding self referentialtables.consider we have a "Person" table that stores data about employees ofan organisation.in case a person change his name or any details we dont want to updateour database by loosing old information and adding new one. what weneed is to hold previous details as well as the new ones.theoratically for me its easy i will just add another row and linkthat row with one of the existing row. to do so i created a relationbetween the "Emp_id" column of "Person" table to itself. so one"Emp_id" could be related to another "Emp_id" in the same table.after doing so i dont know how can i indicate while inserting a recordthat this new record in linked with one of the previous records. meansin insert statement how the relation ship would be added.here i am not sure if i am thinking in the right direction or not aswe may need to add another table or another column to indicate therelation between old an new row. but if we have to add that new columnsay "old_Emp_id" in "Person" table then what does the relationshipbetween "Emp_id" with itself serves.thanksAli
View 4 Replies View RelatedHi all,
WSUS is installed on my windows 2003 server. During the install, parameter DISABLENETWORKPROTOCOLS was not specified, and so no remote connection was possible.
I used SVRNETCN.exe to enable TCP/IP remote connection on port 1433. However it seems not to work.
FROM THE SERVER :
osql -E -S MYSERVERWSUS works fine but
osql -E -S 127.0.0.1WSUS doesn't work, i get the famous error
[DBNETLIB]Serveur SQL spécifié non trouvé.
[DBNETLIB]ConnectionOpen (Connect()).
If i user "osql -L" command, my instance doesn't appear in the list
FROM A CLIENT COMPUTER
osql -E -S MYSERVERWSUS and
osql -E -S MY_SERVER_IPWSUS don't work, i get the same error
I've tried tried to understand for hours, and i'm lost. I thought there may be a problem between SQL and 2003, and read SQL sp3a was required. I ran
select @@version from osql and got result
Microsoft SQL Server 2000 - 8.00.881 (Intel X86)
8.00.881 is not referenced in ms support as a patched version number !!!!!
Can anyone help me please ?