Referencial Integrity Question

Mar 24, 2008

Hi,

Let's say you have these 3 tables

--------------------------------------------------------------

use tempdb
go

create table TableMain (
RowID int primary key identity(1, 1)
, ItemTypeID tinyint NOT NULL
, Details varchar(200) NOT NULL
)
go

create table TableDetails (
DetailRowID int primary key identity(1, 1)
, RowID int NOT NULL
, ItemTypeID tinyint NOT NULL
, Details varchar(200) NOT NULL

)
go

create table ItemTypes (
ItemTypeID tinyint primary key identity(1, 1)
, Details varchar(50) NOT NULL
)
go

create unique nonclustered index IX_TableMain__ItemTypeID__RowID on TableMain (ItemTypeID, RowID)
go

alter table TableDetails
add constraint FK_TableDetails_TableMain__RowID__ItemTypeID foreign key (ItemTypeID, RowID) references TableMain(ItemTypeID, RowID);
go

alter table TableMain
add constraint FK_TableMain_ItemTypes__ItemTypeID foreign key (ItemTypeID) references ItemTypes(ItemTypeID);
go

/*
drop table TableDetails
drop table TableMain
drop table ItemTypes
*/

--------------------------------------------------------------

As you can see TableDetails references TableMain by ItemTypeID and RowID. TableMain also has a foreign key on ItemTypeID.

In this example although there is no references between TableDetails and ItemTypes on ItemTypeID field, referential integrity is still maintain because of the foreign key on TableMain (ItemTypeID, RowID)


So here is my question. Although referential integrity is maintain with this structure, would you guys still create a foreign key on TableDetails (ItemTypeID), i.e.:

alter table TableDetails
add constraint FK_TableDetails_ItemTypes__ItemTypeID foreign key (ItemTypeID) references ItemTypes(ItemTypeID);
go




There might not be any right or wrong, it might be a personal preference sort of thing. To me it seems performance wise it's better to not create this extra contraints since it doesn't add any additional integrity, on the other hand when looking at a DB schema this extra constraint might help understanding what's going on. Also perhaps it helps SQL Server in picking the right execution plan but that I am not sure.

Perhaps the solution is to create the constraint with a NOCHECK on it... is it?

View 14 Replies


ADVERTISEMENT

Cross Database Referencial Integrity

Feb 12, 2008

Using 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

View 9 Replies View Related

Multiple Database / Cross Database Referencial Integrity (foreign Keys)

Feb 12, 2008

Using 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

View 2 Replies View Related

DataBase Referencial Intergrity Check

Jul 30, 2007

I allow the user to delete record1 from SQL Table1 and record2 from Table2. The only problem is, record1 and record2 refers to record3 in Table3 and I can´t allow the user to delete record1 if the is a field in record3 with record1 ref. code. I can´t set FK between them cuz there is more than one reference to the same field.
 Can someone point the best solution for my problem?

View 3 Replies View Related

Referential Integrity Constraints W/o Referential Integrity In The Db?

Mar 16, 2007

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.

View 2 Replies View Related

Do I Need More Integrity On My DB?

Jul 5, 2004

I am not sure I need more integrity on my DB. My DDL are down below.
thanks

************************************************** *****

create table person(
personId int identity(1,1) primary key,
fName varchar(25) not null,
mI char(1) null,
lName varchar(25) not null
);


create table student(
studentId char(4) not null primary key,
personId int not null
);


alter table student
add constraint fk_person_student
foreign key (personId)
references person (personId)
;

create table instructor(
instructorId char(4) not null primary key,
instructorQual varchar(100) not null,
personId int not null
);

alter table instructor
add constraint fk_person_instructor
foreign key (personId)
references person (personId)
;

create table contract(
contractNum int identity(1,1) primary key,
contractDate smalldatetime not null,
tuition money not null,
studentId char(4) not null foreign key references student (studentId),
contactId int not null foreign key references contact (contactId)
);

create table contact(
contactId int not null primary key,
fName varchar(25) not null,
mI char(1) null,
lName varchar(25) not null,
street varchar(50) not null,
city varchar(25) not null,
state char(2) not null,
zip char(5) not null,
relationship varchar(25) not null,
phNum char(12) not null,
emailAdd varchar(50) null,
);

create table class(
classNum char(4) not null primary key,
className varchar(25) not null,
classDay char(3) not null,
classTime char(8) not null,
testNum char(5) not null
);


alter table class
add constraint fk_class_testnum
foreign key (testNum)
references test (testNum)
;

create table discount(
discountNum char(3) primary key,
discountDesc varchar(100) not null,
discountPer decimal(3,2) not null
);

create table test(
testNum char(5) primary key,
testName varchar(50) not null,
testDate smalldatetime not null,
testFee money not null,
);

create table studentClass(
studentId char(4) not null,
classNum char(4) not null,
pass char(1) not null
);

alter table studentClass
add constraint pk_studentclass primary key clustered (studentId, classNum)
;


alter table studentClass
add constraint fk_studentclass_studenttid
foreign key (studentId)
references student(studentId)
;

alter table studentClass
add constraint fk_studentclass_classnum
foreign key (classNum)
references class(classNum)
;

create table contractDiscount(
contractNum int not null,
discountNum char(3) not null
);

alter table contractDiscount
add constraint pk_contractdiscount primary key clustered (contractNum, discountNum)
;

alter table contractDiscount
add constraint fk_contractdiscount_contractnum
foreign key (contractNum)
references contract(contractNum)
;

alter table contractDiscount
add constraint fk_contractdiscount_discountnum
foreign key (discountNum)
references discount(discountNum)
;

create table instructorClass(
instructorId char(4) not null,
classNum char(4) not null,
);


alter table instructorClass
add constraint pk_instructorclass primary key clustered (instructorId, classNum)
;

alter table instructorClass
add constraint fk_instructorclass_instructorid
foreign key (instructorId)
references instructor(instructorId)
;

alter table instructorClass
add constraint fk_instructorclass_classnum
foreign key (classnum)
references class(classnum)
;

View 2 Replies View Related

MDF Integrity

Jun 8, 2007

Hi all,



Is there any way to check the integrity of .Mdf file before attaching it to a database means to check whether its valid (or) not.



Thanks.



//Najeed

View 2 Replies View Related

SQL Server And Integrity

Jan 23, 2004

Where should tests for data integrity be done, a few examples:

Inserting data but the underlying data has changed?

Adding data, say an order item row, but since going to that screen the order (and as a result all its order items as well) have been deleted?

It's just I'm starting to see even the simplest of stored procedures as being quite complicated. What puzzles me is a I see lots of INSERT stored procedures with none of this checking in, or returning error codes?

So are they badly done or am I missing somethign?

View 3 Replies View Related

Referential Integrity ?

Aug 11, 2001

Question:
What is used to enforce referential integrity ?
Answer: Triggers; Foriegn Keys.
what is Foreign Keys ?

View 1 Replies View Related

Referential Integrity

Oct 17, 2001

How do you enforce referential integrity in SQL between tables?

Thanks.

View 1 Replies View Related

DTS Integrity Violation

Jun 12, 2000

I having a problem importing a text file into an existing table using the DTS import wizard. The problem I am having is, I am getting an error message stating: Integrity violation: attempt to insert null data or data which violates constraints. The column the error is referenced to is an identity field and I am not trying to insert any data into the field. I have the allow insert identity box checked in the transformation section. Does anyone know about how to solve this problem.
Thanks
James

View 1 Replies View Related

Integrity Checks

Aug 21, 2002

On weekends I have Integrity Checks scheduled to run. Many of these fail for individual databases because users do not log off and the databases cannot be switched to single user mode.

I have checked Books-on-line and have not yet stumbled onto a TSQL command that breaks the connections.

Is there a TSQL command to do this? If not, how can these connections be broken?

View 2 Replies View Related

I Have Referential Integrity. Now What

Feb 26, 2008

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?

View 1 Replies View Related

Integrity Job Error

Sep 6, 2004

Hi folks,

I created a job to check the integrity of my databases every week using SQL Server Maintenance Plan Wizard.
The job is failing every time...
For tb_basico database it works fine, but with the other one (tb_cep) it doesn't work...

Does someone have an idea to solve this problem?

The message is:

[1] Database tb_basico: Check Data and Index Linkage...

** Execution Time: 0 hrs, 0 mins, 11 secs **

[Microsoft SQL-DMO (ODBC SQLState: 42000)] Error 5070: [Microsoft][ODBC SQL Server Driver][SQL Server]Database state cannot be changed while other users are using the database 'tb_cep'
[Microsoft][ODBC SQL Server Driver][SQL Server]ALTER DATABASE statement failed.
[Microsoft][ODBC SQL Server Driver][SQL Server]sp_dboption command failed.
[2] Database tb_cep: Check Data and Index Linkage...
[Microsoft SQL-DMO (ODBC SQLState: 42000)] Error 7919: [Microsoft][ODBC SQL Server Driver][SQL Server]Repair statement not processed. Database needs to be in single user mode.

The following errors were found:

[Microsoft][ODBC SQL Server Driver][SQL Server]Repair statement not processed. Database needs to be in single user mode.
** Execution Time: 0 hrs, 0 mins, 1 secs **

View 1 Replies View Related

Referential Integrity

Oct 26, 2004

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

View 5 Replies View Related

Referential Integrity

Feb 1, 2008

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????

View 2 Replies View Related

Referential Integrity

Dec 23, 2005

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 Related

Check Integrity

Jul 20, 2005

Hi,What methods can we use to check the integrity problems? Some records in mydatabase are having Foreign Keys but the database doesn't have any relatedrecords with required Primary Keys. I need to scan the whole database anddelete (maybe with backup, maybe not) all wrong records.Who can I do that? Is it need to write my own application to do that or wehave some standard way to fix these problems? I'm not a databaseadministrator and don't know these ways (yet). Can somebody help me withadvice?Thanks.Dmitri Shvetsov

View 4 Replies View Related

Integrity With Multiple Commands

Aug 10, 2006

How can I make sure that a couple of commands are either all executed on the database or none of them. For example right now I have an insert, update and delete command. I'm calling each of them with a SqlCommand. So I am afraid that that one of them might be executed, then there's a bad connection and the other two are not. How can I prevent this so that only all commands or nothing is executed on the database?

View 2 Replies View Related

Integrity Checks Failing

Apr 21, 2003

I have a few databases on this Windows 2000 Server running
SQL 2000 which were detached from SQL 7.0 and attached to
SQL 2000.
The problem is the Maintenance Plans (Integrity Checks
keep failing on SQL 2000. I 'DTS'ed a SQL 7.0 database to
this SQL 2000 server and ran the Maintenance Plans on that
database. Works fine only for the DTS'ed database.
What am I missing ???
:confused:

View 5 Replies View Related

Referential Integrity Done By Trigger

Nov 10, 1998

I'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 Related

Integrity Checks Job Failed

Jul 29, 2004

Hello, I had a DB Maintenance plan, the schedule is every day, but today I found teh 'Integrity checks job is failed". What is that mean? How to check this. Thanks.

View 14 Replies View Related

Integrity Checks Job Failed

May 10, 2006

Activity: Check Data and Index Linkage
Error Number: 3624
Severity: 20
State: 1

The errorlog has this:

SQL Server Assertion: File: <p:sqltdbmsstorengdrsinclude
ecord.inl>, line=1447
Failed Assertion = 'm_SizeRec > 0 && m_SizeRec <= MAXDATAROW'.

There is a dump file generated also.

I had run DBCC CHECKDB and no error is found.

Any help is appreciated.

Thanks

View 3 Replies View Related

Integrity Checks Job Failing

May 7, 2007

Hi,

SQl Server 7

I have Daily User DB Integrity Checks job running daily
From past 2 days i am getting below error.

[Microsoft][ODBC SQL Server Driver][SQL Server]CHECKDB found 0 allocation errors and 35 consistency errors in table 'Prod_Hist' (object ID 2098106515).
[Microsoft][ODBC SQL Server Driver][SQL Server]CHECKDB found 0 allocation errors and 99 consistency errors in database 'Ucatalog'.
[Microsoft][ODBC SQL Server Driver][SQL Server]repair_allow_data_loss is the minimum repair level for the errors found by DBCC CHECKDB (Ucatalog repair_fast).
[Microsoft][ODBC SQL Server Driver][SQL Server]DBCC execution completed. If DBCC printed error messages, contact your system administrator.


Please suggest..

Thanks in Advance
Adil

View 1 Replies View Related

SQL 2012 :: How To Check RI Integrity

Jun 1, 2015

I have a database in the 3rd normalized form. There is a need to load rows into a child table. To avoid having to drop RI, an ALTER TABLE WITH NOCHECK is being used. I am looking for a way to verify the integrity after the load is complete. After the load an ALTER TABLE WITH CHECK will be executed. Can I used DBCC to verify, that no orphaned child rows were loaded? If so, which parms would I have to use with DBCC?

View 0 Replies View Related

Referential Integrity Without Foreign Key

Apr 21, 2008

What ate the method/techniques i can use for enforcing referential integrity, Without using foreign key constraints ?

View 7 Replies View Related

Data Integrity Using Constraints

Feb 7, 2006

Hello,

I am fairly new to SQL, so I have a few questions that may sound odd. First of all, I am trying to restrict users to putting in a three character code as an id item, or their team abbreviation. Here is the table definition:

CREATE TABLE TEAMS{
city varchar(20) NOT NULL,
name varchar(20) NOT NULL,
id varchar(3) NOT NULL};

Here is my code for adding the constraint

ALTER TABLE TEAMS
ADD CONSTRAINT Chk_id CHECK (id = `[A-Z][A-Z][A-Z]`);

Here is the error that I get when trying to execute this statement:

Msg 547, Level 16, State 0, Line 1
ALTER TABLE statement conflicted with COLUMN CHECK constraint 'Chk_id'. The conflict occurred in database 'statbookdb', table 'cabateams', column 'id'.

I am using SQL 2005 EM if this makes any difference.

My other question is in regards to once the constraints have been put in. Is there a way to make SQL throw a message out when a user violates a constraint? Right now, I have a numerical constraint in and whenever I violate it, all that happens is a "This page cannot be displayed" error. It doesn't make sense if you can only do this on the front end, as I don't see the point in enforcing it on the backend if there is no way to notify the user.

Thank you all in advance!

View 8 Replies View Related

How Do I Display Integrity Constraints I Set?

Nov 14, 2007

im having a bit of a problem displaying the integrity constraints i have set. I need to show the table name, contraint name and contraint type, but i cant find out how to do this anywhere.

can anyone help?

thanks

View 6 Replies View Related

Check Database Integrity

Jan 22, 2008

im trying to set up maintenance plan for the check database integrity...

In sql 2000 you get a nice little log in SQL Logs
DBCC CHECKDB (WSS_Search_db3) executed by xxx found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 1 seconds.

But in SQL 2005
Im not getting a nice log of this but getting it against some system database and not the database i selected

Date1/22/2008 5:19:43 PM
LogSQL Server (Current - 1/22/2008 5:19:00 PM)
Sourcespid84
Message
DBCC CHECKDB (mssqlsystemresource) WITH no_infomsgs executed by XXX found 0 errors and repaired 0 errors. Elapsed time: 0 hours 0 minutes 1 seconds.

Anyone got this to work?
Trying to get the same message i got for SQL 2000 or at least so i can confirm it ran.

View 13 Replies View Related

Integrity Check Failed

Mar 13, 2008

on sql server 2000, try to do integrity check on several database once a week but failed, what would be main area to look up? thank you

View 3 Replies View Related

Integrity Between Table And View

Jul 23, 2005

It is possible to drop the table without dropping the view referencingit. How do I force integrity?Madhivanan

View 9 Replies View Related

Referential Integrity Problem

Jun 3, 2006

I'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 Related

WDAC Integrity Check

May 21, 2008

Hello everyone,

Currently having some issues with my laptop. I'm no computer expert / programmer so please bear with me.

It is a Vista Home Premium based machine that was purchased about 6 months ago. I'm having issues with an application that relies on WDAC to work. The application worked perfectly in the past and I just recently tried to use it again and it doesn't get past the "Loading Application" screen.

From the company website, they make it clear that anyone using the software has to make sure to run the Windows update to bring the DOT NET framework and MDAC to their latest revisions.

Now, I know that MDAC has been replaced by WDAC to run under Vista. However, I learned that only after trying, for a completely different reason, to install MDAC 2.8 SP1 (I know, dumb idea).

All this to end up saying I'm pretty sure something was screwed up in my WDAC when I tried installing MDAC. I would like to know if there is any way to verify the WDAC installation integrity, basically a Microsoft Component Checker equivalent under Vista.

Thanks a lot for helping a newbie !!

View 2 Replies View Related







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