Showing posts with label integrity. Show all posts
Showing posts with label integrity. Show all posts

Wednesday, March 21, 2012

Referential Integrity with empty string and ZERO

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

If you place a foreign key constraint on a column, zero is only a valid value if there is a zero in foreign key table. The same applies to empty strings.

If the foreign key value of a particular row is unknown (or it doesnt have one), that's where the use of null comes in. Of course a NOT NULL constraint used in conjunction with the FK constraint can prevent the use of nulls (forcing a valid FK value).

To the best of my knowledge, it's not possible to change this behavior.

Referential Integrity with empty string and ZERO

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

If you place a foreign key constraint on a column, zero is only a valid value if there is a zero in foreign key table. The same applies to empty strings.

If the foreign key value of a particular row is unknown (or it doesnt have one), that's where the use of null comes in. Of course a NOT NULL constraint used in conjunction with the FK constraint can prevent the use of nulls (forcing a valid FK value).

To the best of my knowledge, it's not possible to change this behavior.

Referential Integrity problem

I'm using Microsoft SQL Server Management Studio Express 9.00.2047.00
and expriencing problems with setting referential integrity on a link
table. The tables' schema is as follows:
--------------------
CREATE TABLE competencies (
CID bigint identity(1,1) CONSTRAINT pk_CID PRIMARY KEY,
LockedBy bigint DEFAULT 0 NOT NULL
CONSTRAINT fk_UserID
REFERENCES usr_info(userID)
ON DELETE SET DEFAULT
ON 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 NULL
CONSTRAINT fkCID_ch
REFERENCES competencies(CID)
ON DELETE CASCADE
ON UPDATE CASCADE,
ApprovedBy bigint default 0 NOT NULL
CONSTRAINT fkUserID_ch
REFERENCES usr_info(userID)
ON DELETE SET DEFAULT -- NO delete if user is deleted
ON UPDATE CASCADE
)
------------------
When I execute the above I get the following error message.

Msg 1785, Level 16, State 0, Line 1
Introducing FOREIGN KEY constraint 'fkUserID_ch' on table
'competency_hdr' may cause cycles or multiple cascade paths. Specify
ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN
KEY constraints.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

Now, if i swap the fields around then the error message changes to
that of the fkCID field.

Basically what I want is:
when I delete a competency record I need all references to this record
to be deleted.
when I delete a user I want to set the foreign key to zero (the record
must remain on the database).

Obviously there is something I'm missing here. Any advice, anyone?
-------------------
jnorthau@.yourpantsyahoo.com.au : Remove your pants to reply
-------------------Jeff North (jnorthau@.yahoo.com.au) writes:
> When I execute the above I get the following error message.
> Msg 1785, Level 16, State 0, Line 1
> Introducing FOREIGN KEY constraint 'fkUserID_ch' on table
> 'competency_hdr' may cause cycles or multiple cascade paths. Specify
> ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN
> KEY constraints.
> Msg 1750, Level 16, State 0, Line 1
> Could not create constraint. See previous errors.
> Now, if i swap the fields around then the error message changes to
> that of the fkCID field.
> Basically what I want is:
> when I delete a competency record I need all references to this record
> to be deleted.
> when I delete a user I want to set the foreign key to zero (the record
> must remain on the database).
> Obviously there is something I'm missing here. Any advice, anyone?

SQL Server is extremly conservative with cascading foreign keys. If there
is the slightest suspecion there could be trouble, it won't permit you
define the cascade path. I can't really say what might be the problem
in this case, but I guess that if you add triggers into the mix, there
can be intersting results.

One way to handle cascading updates and deletes is to use triggers. The
drawback with this is that you cannot have any declarative referential
integrity at all, as constraints are checked before triggers fire.

A better approach is probably to use a stored procedure that performs
the cascade from bottom up. That is, it first deletes the children and
then the children.

By the way, having 0 as a dummy user for "no one at all", is probably
not the best design. I would rather use NULL for this.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||On Sat, 3 Jun 2006 17:34:14 +0000 (UTC), in
comp.databases.ms-sqlserver Erland Sommarskog <esquel@.sommarskog.se>
<Xns97D7C71728295Yazorman@.127.0.0.1> wrote:

>| Jeff North (jnorthau@.yahoo.com.au) writes:
>| > When I execute the above I get the following error message.
>| >
>| > Msg 1785, Level 16, State 0, Line 1
>| > Introducing FOREIGN KEY constraint 'fkUserID_ch' on table
>| > 'competency_hdr' may cause cycles or multiple cascade paths. Specify
>| > ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN
>| > KEY constraints.
>| > Msg 1750, Level 16, State 0, Line 1
>| > Could not create constraint. See previous errors.
>| >
>| > Now, if i swap the fields around then the error message changes to
>| > that of the fkCID field.
>| >
>| > Basically what I want is:
>| > when I delete a competency record I need all references to this record
>| > to be deleted.
>| > when I delete a user I want to set the foreign key to zero (the record
>| > must remain on the database).
>| >
>| > Obviously there is something I'm missing here. Any advice, anyone?

Thanks for your response, much appreciated.

>| SQL Server is extremly conservative with cascading foreign keys. If there
>| is the slightest suspecion there could be trouble, it won't permit you
>| define the cascade path.

Thank goodness it's the app. I thought I was misunderstanding
something.

>| I can't really say what might be the problem
>| in this case, but I guess that if you add triggers into the mix, there
>| can be intersting results.

No triggers at present but it looks as though triggers might be the
only option.

>| One way to handle cascading updates and deletes is to use triggers. The
>| drawback with this is that you cannot have any declarative referential
>| integrity at all, as constraints are checked before triggers fire.
>|
>| A better approach is probably to use a stored procedure that performs
>| the cascade from bottom up. That is, it first deletes the children and
>| then the children.

More maintenance woes :-(

>| By the way, having 0 as a dummy user for "no one at all", is probably
>| not the best design. I would rather use NULL for this.

Agreed but there are always exceptions to the rule :-)
-------------------
jnorthau@.yourpantsyahoo.com.au : Remove your pants to reply
-------------------|||Jeff North (jnorthau@.yahoo.com.au) writes:
> On Sat, 3 Jun 2006 17:34:14 +0000 (UTC), in
> comp.databases.ms-sqlserver Erland Sommarskog <esquel@.sommarskog.se>
><Xns97D7C71728295Yazorman@.127.0.0.1> wrote:
>>| I can't really say what might be the problem
>>| in this case, but I guess that if you add triggers into the mix, there
>>| can be intersting results.
> No triggers at present but it looks as though triggers might be the
> only option.

What I wanted to say that combination of cascading DRI (had it been
permitted) and triggers in this case could have lead to interesting
results. And since a trigger could be added later, my suspicion that the
mere possibility is enough to disallow the multiple cascade path.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||On Sun, 4 Jun 2006 16:22:48 +0000 (UTC), in
comp.databases.ms-sqlserver Erland Sommarskog <esquel@.sommarskog.se>
<Xns97D8BAFABD743Yazorman@.127.0.0.1> wrote:

>| Jeff North (jnorthau@.yahoo.com.au) writes:
>| > On Sat, 3 Jun 2006 17:34:14 +0000 (UTC), in
>| > comp.databases.ms-sqlserver Erland Sommarskog <esquel@.sommarskog.se>
>| ><Xns97D7C71728295Yazorman@.127.0.0.1> wrote:
>| >>| I can't really say what might be the problem
>| >>| in this case, but I guess that if you add triggers into the mix, there
>| >>| can be intersting results.
>| >
>| > No triggers at present but it looks as though triggers might be the
>| > only option.
>|
>| What I wanted to say that combination of cascading DRI (had it been
>| permitted) and triggers in this case could have lead to interesting
>| results.

I could well imagine what sort of 'problems' could arise :-)

>| And since a trigger could be added later, my suspicion that the
>| mere possibility is enough to disallow the multiple cascade path.
-------------------
jnorthau@.yourpantsyahoo.com.au : Remove your pants to reply
-------------------|||Have you considered a relational design? It would have actual keys of
a proper data type and some research about standards? Do you really
know anyone with a first_name that is VARCHAR(100)? Why did you think
that IDENTITY can ever, ever be a key? And a key with a DEFAULT?
Defaults are for attributes which can have multiple occurrences of
values. And why did think that you need a BIGINT so you can have more
users than the entire population of Earth?

Can you use the "Dictionary of Occupational Titles" for
Competencies? What research did you do?

Why is a user an attribute of a Competency? Only Fred can be a
carpenter? Why do you use bit flags in SQL?

CREATE TABLE Competencies
(dot_code CHAR(6) NOT NULL PRIMARY KEY,
dot_description VARCHAR(25) NOT NULL);

Shouldn't there be a user attribute for approval powers? You did not
show one.

CREATE TABLE Users
(user_id INTEGER NOT NULL PRIMARY KEY, -- needs research!
first_name VARCHAR(25) NOT NULL,
last_name VARCHAR(25) NOT NULL);

>> When I delete a competency record [sic] I need all references to this record [sic] to be deleted. When I delete a user I want to set the foreign key to zero (the record [sic] must remain on the database). <<

One of the first steps to learning to think in SQL is that a row and a
record are totally different. Until then, you will keep setting flags
(like your "foreign keys are set to zero" violation of 1NF).

You are trying to keep a history, so you need durations in the data
model.

CREATE TABLE Assignments
(user_id INTEGER NOT NULL
REFERENCES Users(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE,
dot_code CHAR(6) NOT NULL
REFERENCES Competencies(dot_code)
ON UPDATE CASCADE,
assignment_date DATETIME
DEFAULT CURRENT_TIMESTAMP NOT NULL,
completion_date DATETIME
DEFAULT CURRENT_TIMESTAMP
CHECK (assignment_date < completion_date),
PRIMARY KEY (user_id, dot_code, assignment_date),
approving_user_id INTEGER NOT NULL
REFERENCES Users(user_id)
ON DELETE CASCADE
ON UPDATE CASCADE);

This is proper SQL, but SQL Server will not allow it. The product
worries about cycles in DRI.

One kludge might be to split out the approvers

CREATE TABLE Competencies
(dot_code CHAR(6) NOT NULL PRIMARY KEY,
dot_description VARCHAR(25) NOT NULL);

CREATE TABLE Users
(user_id INTEGER NOT NULL,
user_type CHAR(1) DEFAULT 'R' NOT NULL
CHECK (user_type IN ('R', 'A')), -- r= regular, a = approver
PRIMARY KEY (user_id, user_type),
first_name VARCHAR(25) NOT NULL,
last_name VARCHAR(25) NOT NULL);

CREATE TABLE Approvers
(user_id INTEGER NOT NULL,
user_type CHAR(1) NOT NULL
CHECK (user_type = 'A'),
PRIMARY KEY (user_id, user_type),
FOREIGN KEY (user_id, user_type)
REFERENCES Users (user_id, user_type)
ON DELETE CASCADE
ON UPDATE CASCADE);

CREATE TABLE RegularUsers
(user_id INTEGER NOT NULL,
user_type CHAR(1) NOT NULL
CHECK (user_type = 'R'),
PRIMARY KEY (user_id, user_type),
FOREIGN KEY (user_id, user_type)
REFERENCES Users (user_id, user_type)
ON DELETE CASCADE
ON UPDATE CASCADE);

CREATE TABLE Assignments
(user_id INTEGER NOT NULL,
user_type CHAR(1) NOT NULL CHECK (user_type = 'R')
FOREIGN KEY (iser_id, user_type)
REFERENCES RegularUsers(user_id, user_type)
ON DELETE CASCADE
ON UPDATE CASCADE,
dot_code CHAR(6) NOT NULL
REFERENCES Competencies(dot_code)
ON UPDATE CASCADE,
assignment_date DATETIME
DEFAULT CURRENT_TIMESTAMP NOT NULL,
completion_date DATETIME
DEFAULT CURRENT_TIMESTAMP
CHECK (assignment_date < completion_date),
PRIMARY KEY (user_id, dot_code, assignment_date),
approving_user_id INTEGER NOT NULL,
user_type CHAR(1) NOT NULL CHECK (user_type = 'A')
FOREIGN KEY (user_id, user_type)
REFERENCES ApprovingUsers(user_id, user_type)
ON DELETE CASCADE
ON UPDATE CASCADE);|||On 5 Jun 2006 10:52:35 -0700, in comp.databases.ms-sqlserver
"--CELKO--" <jcelko212@.earthlink.net>
<1149529955.519214.221850@.i39g2000cwa.googlegroups. com> wrote:

>| Have you considered a relational design? It would have actual keys of
>| a proper data type and some research about standards? Do you really
>| know anyone with a first_name that is VARCHAR(100)? Why did you think
>| that IDENTITY can ever, ever be a key? And a key with a DEFAULT?
>| Defaults are for attributes which can have multiple occurrences of
>| values. And why did think that you need a BIGINT so you can have more
>| users than the entire population of Earth?

Please don't jump to unnecassary, and wrong, conclussions.
I'm converting the database from mySQL4.0.21 to MSSQL therefore the
schema hasn't been fully optimised.

>| Can you use the "Dictionary of Occupational Titles" for
>| Competencies? What research did you do?

Again, you've seen 3 partial tables and jump to unnecessary
conclusions.

>| Why is a user an attribute of a Competency? Only Fred can be a
>| carpenter? Why do you use bit flags in SQL?

They, bit flags, are the most appropriate type for true/false or
yes/no or in/out data fields, yes?

>| CREATE TABLE Competencies
>| (dot_code CHAR(6) NOT NULL PRIMARY KEY,
>| dot_description VARCHAR(25) NOT NULL);
>|
>| Shouldn't there be a user attribute for approval powers? You did not
>| show one.
>|
>| CREATE TABLE Users
>| (user_id INTEGER NOT NULL PRIMARY KEY, -- needs research!
>| first_name VARCHAR(25) NOT NULL,
>| last_name VARCHAR(25) NOT NULL);

Again, you're jumping to wrong conclusions.
The usr_info table is for registered users that can add, delete and
modify data. I need to track who has done what as part of the business
rules for the application (as can be seen by the ApprovedBy and
LockedBy fields).

>| >> When I delete a competency record [sic] I need all references to this record [sic] to be deleted. When I delete a user I want to set the foreign key to zero (the record [sic] must remain on the database). <<
>|
>| One of the first steps to learning to think in SQL is that a row and a
>| record are totally different.

Please explain this further.

>| Until then, you will keep setting flags
>| (like your "foreign keys are set to zero" violation of 1NF).
>|
I've snipped your code but will study it further.
-------------------
jnorthau@.yourpantsyahoo.com.au : Remove your pants to reply
-------------------

Referential Integrity practices for complex Database

I am a database Engineer for a company that has relatively large and complex
SQL Server databases.
The DB Engineers group seem to have different opinions about weather or not
we should enforce referential integrity to our database.(In fact we have
databases that are both ways). Both aspects seem to have pro's and cons.
I am trying to find out what are the common practices adopted by other
companies in similar situation. Do you enforce the referential integrity? If
so how do you deal with the heightened complexity of back end updates when
necessary? On the other hand if you did not, how do we enforce accuracy?
Your input in this is very much appreciated.Hi
Wow , I thought that DB Engineer would not has any doubt for this question.
In my company i have always been creating a primary key to every table and
foreign key to enforce the referential integrity. Benefits? your querie's
perfomance will be improved , it will prevent from unwanted deletion ,
create a diagram to see a whole picture of your database's relatioship
and......
Well , BOL has pretty good description about andvatages to enforce the
referential integrity.
"bluefish" <bluefish@.discussions.microsoft.com> wrote in message
news:72BAFD60-A99A-4CE9-83D1-C52C78BE8B38@.microsoft.com...
>I am a database Engineer for a company that has relatively large and
>complex
> SQL Server databases.
> The DB Engineers group seem to have different opinions about weather or
> not
> we should enforce referential integrity to our database.(In fact we have
> databases that are both ways). Both aspects seem to have pro's and cons.
> I am trying to find out what are the common practices adopted by other
> companies in similar situation. Do you enforce the referential integrity?
> If
> so how do you deal with the heightened complexity of back end updates when
> necessary? On the other hand if you did not, how do we enforce accuracy?
> Your input in this is very much appreciated.
>|||bluefish wrote:
> I am a database Engineer for a company that has relatively large and complex
> SQL Server databases.
> The DB Engineers group seem to have different opinions about weather or not
> we should enforce referential integrity to our database.(In fact we have
> databases that are both ways). Both aspects seem to have pro's and cons.
> I am trying to find out what are the common practices adopted by other
> companies in similar situation. Do you enforce the referential integrity? If
> so how do you deal with the heightened complexity of back end updates when
> necessary?
The purpose of referential integrity is to implement business rules and
ensure that your database accurately and consistently models the real
world. The fact that your engineers have to ask this question suggests
that either they don't understand your business or that they don't care
about data integrity.
> On the other hand if you did not, how do we enforce accuracy?
Better ask the people who designed your systems without any
integrity...
--
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--

Referential Integrity practices for complex Database

I am a database Engineer for a company that has relatively large and complex
SQL Server databases.
The DB Engineers group seem to have different opinions about weather or not
we should enforce referential integrity to our database.(In fact we have
databases that are both ways). Both aspects seem to have pro's and cons.
I am trying to find out what are the common practices adopted by other
companies in similar situation. Do you enforce the referential integrity? If
so how do you deal with the heightened complexity of back end updates when
necessary? On the other hand if you did not, how do we enforce accuracy?
Your input in this is very much appreciated.Hi
Wow , I thought that DB Engineer would not has any doubt for this question.
In my company i have always been creating a primary key to every table and
foreign key to enforce the referential integrity. Benefits? your querie's
perfomance will be improved , it will prevent from unwanted deletion ,
create a diagram to see a whole picture of your database's relatioship
and......
Well , BOL has pretty good description about andvatages to enforce the
referential integrity.
"bluefish" <bluefish@.discussions.microsoft.com> wrote in message
news:72BAFD60-A99A-4CE9-83D1-C52C78BE8B38@.microsoft.com...
>I am a database Engineer for a company that has relatively large and
>complex
> SQL Server databases.
> The DB Engineers group seem to have different opinions about weather or
> not
> we should enforce referential integrity to our database.(In fact we have
> databases that are both ways). Both aspects seem to have pro's and cons.
> I am trying to find out what are the common practices adopted by other
> companies in similar situation. Do you enforce the referential integrity?
> If
> so how do you deal with the heightened complexity of back end updates when
> necessary? On the other hand if you did not, how do we enforce accuracy?
> Your input in this is very much appreciated.
>sql

Referential Integrity Performance

How does Sql Server do referential integrity checks? My reason for asking
this is a conceptual theory that a referential integrity check against a
narrow row would be faster than on a wider row because there would be more
rows on a page, hence any mapping structures that SQL Server would use
internally to check RI would also be much smaller reducing seek and traverse
time?
--
Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Netexamnotes <TVanover@.discussions.microsoft.com> wrote in
news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com:

> How does Sql Server do referential integrity checks? My reason for
> asking this is a conceptual theory that a referential integrity check
> against a narrow row would be faster than on a wider row because there
> would be more rows on a page, hence any mapping structures that SQL
> Server would use internally to check RI would also be much smaller
> reducing seek and traverse time?
I'm not sure, but I feel pretty comfortable that this is done the same way
as a query, that is checking all the columns at the same time. Reson for
this is mainly performance, since you can do with one scan of the data
instead of several, which of course could hurt performance even more.
Another reason for my thought is the fact that indexes can be used to
improve the performance of the integrity checks.
Ole Kristian Bangs
MCT, MCDBA, MCDST, MCSE:Security, MCSE:Messaging, MCTS, MCITP|||The RI check would be against the key itself, which is supported by a unique
index. Key lookups are generally quick. It doesn't really matter about the
width of the table's rows. The key's width, coupled with disk I/O speed,
amount of memory and CPU speed are the overall determining factor.
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Toronto, ON Canada
.
"TVanover" <TVanover@.discussions.microsoft.com> wrote in message
news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com...
How does Sql Server do referential integrity checks? My reason for asking
this is a conceptual theory that a referential integrity check against a
narrow row would be faster than on a wider row because there would be more
rows on a page, hence any mapping structures that SQL Server would use
internally to check RI would also be much smaller reducing seek and traverse
time?
--
Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net|||Well if the RI is going against a clustered index then it would- could matte
r
as this is associated with a full row of data at the leaf level. Remember
that rows are stored on pages and pages are stored on extents. How many time
s
does a narrow row have to be traversed vs a wide row given that I can only
get 8060 bytes of row data per page?
Secondly if there is a black box structure that holds a mapping of the key
location then there will ceratinly be fewer leaf levels in that structure as
there are more rows per page on a narrow row?
Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
"Tom Moreau" wrote:

> The RI check would be against the key itself, which is supported by a uniq
ue
> index. Key lookups are generally quick. It doesn't really matter about t
he
> width of the table's rows. The key's width, coupled with disk I/O speed,
> amount of memory and CPU speed are the overall determining factor.
> --
> Tom
> ----
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Toronto, ON Canada
> ..
> "TVanover" <TVanover@.discussions.microsoft.com> wrote in message
> news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com...
> How does Sql Server do referential integrity checks? My reason for asking
> this is a conceptual theory that a referential integrity check against a
> narrow row would be faster than on a wider row because there would be more
> rows on a page, hence any mapping structures that SQL Server would use
> internally to check RI would also be much smaller reducing seek and traver
se
> time?
> --
> Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
>|||But you are not traversing all of the leaf node 'data' pages, you are only
traversing the upper intermediate (or 'index') pages to get to the
datapages. And yes, a wide data row will result in fewer rows of data on a
page and consequently more intermediate pages -that will be compensated for
in the index.
From BOL on 'Clustered Indexes'...
"For a clustered index, sysindexes.root points to the top of the clustered
index. SQL Server navigates down the index to find the row corresponding to
a clustered index key. "
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"TVanover" <TVanover@.discussions.microsoft.com> wrote in message
news:A768C36E-7AFA-4F47-92E6-A453BB4DC1FA@.microsoft.com...[vbcol=seagreen]
> Well if the RI is going against a clustered index then it would- could
> matter
> as this is associated with a full row of data at the leaf level. Remember
> that rows are stored on pages and pages are stored on extents. How many
> times
> does a narrow row have to be traversed vs a wide row given that I can only
> get 8060 bytes of row data per page?
> Secondly if there is a black box structure that holds a mapping of the key
> location then there will ceratinly be fewer leaf levels in that structure
> as
> there are more rows per page on a narrow row?
> --
> Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
>
> "Tom Moreau" wrote:
>

Referential Integrity Performance

How does Sql Server do referential integrity checks? My reason for asking
this is a conceptual theory that a referential integrity check against a
narrow row would be faster than on a wider row because there would be more
rows on a page, hence any mapping structures that SQL Server would use
internally to check RI would also be much smaller reducing seek and traverse
time?
--
Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net=?Utf-8?B?VFZhbm92ZXI=?= <TVanover@.discussions.microsoft.com> wrote in
news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com:
> How does Sql Server do referential integrity checks? My reason for
> asking this is a conceptual theory that a referential integrity check
> against a narrow row would be faster than on a wider row because there
> would be more rows on a page, hence any mapping structures that SQL
> Server would use internally to check RI would also be much smaller
> reducing seek and traverse time?
I'm not sure, but I feel pretty comfortable that this is done the same way
as a query, that is checking all the columns at the same time. Reson for
this is mainly performance, since you can do with one scan of the data
instead of several, which of course could hurt performance even more.
Another reason for my thought is the fact that indexes can be used to
improve the performance of the integrity checks.
--
Ole Kristian Bangås
MCT, MCDBA, MCDST, MCSE:Security, MCSE:Messaging, MCTS, MCITP|||The RI check would be against the key itself, which is supported by a unique
index. Key lookups are generally quick. It doesn't really matter about the
width of the table's rows. The key's width, coupled with disk I/O speed,
amount of memory and CPU speed are the overall determining factor.
--
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Toronto, ON Canada
.
"TVanover" <TVanover@.discussions.microsoft.com> wrote in message
news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com...
How does Sql Server do referential integrity checks? My reason for asking
this is a conceptual theory that a referential integrity check against a
narrow row would be faster than on a wider row because there would be more
rows on a page, hence any mapping structures that SQL Server would use
internally to check RI would also be much smaller reducing seek and traverse
time?
--
Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net|||Well if the RI is going against a clustered index then it would- could matter
as this is associated with a full row of data at the leaf level. Remember
that rows are stored on pages and pages are stored on extents. How many times
does a narrow row have to be traversed vs a wide row given that I can only
get 8060 bytes of row data per page?
Secondly if there is a black box structure that holds a mapping of the key
location then there will ceratinly be fewer leaf levels in that structure as
there are more rows per page on a narrow row?
--
Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
"Tom Moreau" wrote:
> The RI check would be against the key itself, which is supported by a unique
> index. Key lookups are generally quick. It doesn't really matter about the
> width of the table's rows. The key's width, coupled with disk I/O speed,
> amount of memory and CPU speed are the overall determining factor.
> --
> Tom
> ----
> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
> SQL Server MVP
> Toronto, ON Canada
> ..
> "TVanover" <TVanover@.discussions.microsoft.com> wrote in message
> news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com...
> How does Sql Server do referential integrity checks? My reason for asking
> this is a conceptual theory that a referential integrity check against a
> narrow row would be faster than on a wider row because there would be more
> rows on a page, hence any mapping structures that SQL Server would use
> internally to check RI would also be much smaller reducing seek and traverse
> time?
> --
> Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
>|||But you are not traversing all of the leaf node 'data' pages, you are only
traversing the upper intermediate (or 'index') pages to get to the
datapages. And yes, a wide data row will result in fewer rows of data on a
page and consequently more intermediate pages -that will be compensated for
in the index.
From BOL on 'Clustered Indexes'...
"For a clustered index, sysindexes.root points to the top of the clustered
index. SQL Server navigates down the index to find the row corresponding to
a clustered index key. "
--
Arnie Rowland
"To be successful, your heart must accompany your knowledge."
"TVanover" <TVanover@.discussions.microsoft.com> wrote in message
news:A768C36E-7AFA-4F47-92E6-A453BB4DC1FA@.microsoft.com...
> Well if the RI is going against a clustered index then it would- could
> matter
> as this is associated with a full row of data at the leaf level. Remember
> that rows are stored on pages and pages are stored on extents. How many
> times
> does a narrow row have to be traversed vs a wide row given that I can only
> get 8060 bytes of row data per page?
> Secondly if there is a black box structure that holds a mapping of the key
> location then there will ceratinly be fewer leaf levels in that structure
> as
> there are more rows per page on a narrow row?
> --
> Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
>
> "Tom Moreau" wrote:
>> The RI check would be against the key itself, which is supported by a
>> unique
>> index. Key lookups are generally quick. It doesn't really matter about
>> the
>> width of the table's rows. The key's width, coupled with disk I/O speed,
>> amount of memory and CPU speed are the overall determining factor.
>> --
>> Tom
>> ----
>> Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
>> SQL Server MVP
>> Toronto, ON Canada
>> ..
>> "TVanover" <TVanover@.discussions.microsoft.com> wrote in message
>> news:C8207684-981B-48D4-922B-E5A79B8DFF60@.microsoft.com...
>> How does Sql Server do referential integrity checks? My reason for asking
>> this is a conceptual theory that a referential integrity check against a
>> narrow row would be faster than on a wider row because there would be
>> more
>> rows on a page, hence any mapping structures that SQL Server would use
>> internally to check RI would also be much smaller reducing seek and
>> traverse
>> time?
>> --
>> Timothy A. Vanover MCSD, MCDBA, MCAD, MCSD for .Net
>>

Referential Integrity In Mutiple Tables. Need Help.

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?You have it already...you just need to enforce the relationship with a FOREIGN KEY CONSTRAINT

And please don't tell me that StateID is an entity column...|||I can only relate table 4 with either table 2 or 3 but not both. what do you mean by entity table? Excuse my ignorance.

Thanks|||I'm not sure I follow you...

USE Northwind
GO
SET NOCOUNT ON
CREATE TABLE Table4 (
StateID int PRIMARY KEY
, [Name] varchar(50)
)

CREATE TABLE Table2 (
BillingAddressID int PRIMARY KEY
, StateID int
, OtherFields int
, CONSTRAINT FK_Table2 FOREIGN KEY (StateID) REFERENCES Table4(StateId)
)

CREATE TABLE Table3 (
ShippingAddressID int PRIMARY KEY
, StateID int
, OtherFields int
, CONSTRAINT FK_Table3 FOREIGN KEY (StateID) REFERENCES Table4(StateId)
)
GO

INSERT INTO Table3(ShippingAddressID, StateID) SELECT 1,1
INSERT INTO Table2(BillingAddressID, StateID) SELECT 1,1
GO
INSERT INTO Table4(StateID, [Name]) SELECT 1, 'New Jersey'
GO
INSERT INTO Table3(ShippingAddressID, StateID, OtherFields) SELECT 1,1, 1
INSERT INTO Table2(BillingAddressID , StateID, OtherFields) SELECT 1,1, 1
GO

SELECT 'Table3' AS Source, l.ShippingAddressID, l.StateID, l.OtherFields, r.[Name]
FROM Table3 l
JOIN Table4 r
ON l.StateID = r.StateID
UNION ALL
SELECT 'Table2' AS Source, l.BillingAddressID, l.StateID, l.OtherFields, r.[Name]
FROM Table2 l
JOIN Table4 r
ON l.StateID = r.StateID
GO

SET NOCOUNT OFF
DROP TABLE Table2
DROP TABLE Table3
DROP TABLE Table4
GO|||Oh, I meant IDENTITY Column by the way...not Entity...sorry|||why wouldn't StateID be an identity column?

are you perhaps suggesting that a natural key like NJ would be more suitable?

better hide, because all the surrogate key fanatics are gonna come gunnin' for ya...|||Hey...it's their perogative...let them join till the cows come home...

And there are times for it...but not as many as it's abused...

Here's a question. Would you use an identity column for a phone number? SSN? Stock Market symbol?|||Would you use an identity column for a phone number? SSN? Stock Market symbol?me? never

you must have me confused with those surrogate key fanatics, who blindly require an identity column in every table...

i know a guy on, ahem, another forum web site, who once took a poll on the subject

see Surrogate Keys.The Devils spawn (OK Not really) (http://weblogs.sqlteam.com/brettk/archive/2004/06/09/1530.aspx)

Referential integrity during replication

Hello forum

I like to build a custom replication application for a databasee.
To questions concering this. The idea is to use a mechanim, which updates table by table (in sequence).

During the replication proccess I update a table (table1), which has 1 to 1 refenceto a second table(table2). This new record is unsing a reference which hasn't been entered by this time into table 2. This is hurts the referencial integrity, right?

Would it help to use a transaction for the update in table 1 and table 2, when is the integrity checked? At the end of the transaction, by the command commit transaction?

Is it possible to switch on/off the referential integrity check while a database is running? If yes, are there any side effects beside that the integrity is not propre controlles anymore?

Thanks for your help in advance!

DominikWhat about this:

drop table test1
drop table test2
go
create table test2(id int primary key)
create table test1(id int, rid int)
ALTER TABLE test1 WITH NOCHECK ADD CONSTRAINT
FK1 FOREIGN KEY(rid) REFERENCES dbo.test2(id)
go
insert test2 values(1)
insert test1 values(1,1)
go
ALTER TABLE dbo.test1 NOCHECK CONSTRAINT FK1
go
insert test1 values(1,11) -- works

Referential integrity different databases

I would like to apply referential integrity between two
tables that are not part of the same database.
Is this possible ?You can't do it with foreign key constraints. They are not allowed across
databases.
You can do it with triggers or by only allowing inserts, deletes, and
updates through stored procedures and enforcing the integrity in the
triggers or stored procs. Note that if you do this, there are still some
problematic situations. For example, the triggers and/or stored procs can't
prevent you from restoring one of the databases from last night's backup and
thus breaking the integrity.
Tom
"TheOne" <TheOne@.discussions.microsoft.com> wrote in message
news:61E4E107-5E5C-4D40-9575-D5B8E17D9F04@.microsoft.com...
>I would like to apply referential integrity between two
> tables that are not part of the same database.
> Is this possible ?
>sql

Referential integrity different databases

I would like to apply referential integrity between two
tables that are not part of the same database.
Is this possible ?
You can't do it with foreign key constraints. They are not allowed across
databases.
You can do it with triggers or by only allowing inserts, deletes, and
updates through stored procedures and enforcing the integrity in the
triggers or stored procs. Note that if you do this, there are still some
problematic situations. For example, the triggers and/or stored procs can't
prevent you from restoring one of the databases from last night's backup and
thus breaking the integrity.
Tom
"TheOne" <TheOne@.discussions.microsoft.com> wrote in message
news:61E4E107-5E5C-4D40-9575-D5B8E17D9F04@.microsoft.com...
>I would like to apply referential integrity between two
> tables that are not part of the same database.
> Is this possible ?
>

Referential Integrity Constraints w/o Referential Integrity in the db?

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.

Using a TRIGGER, you can define just about any type of constraint you desire.

However, the referential constraints (PK-FK) will still require relationships between tables.

|||

The problem that I have is that we are working with a highly denormalized database so true constraints on all of our tables are not really an option at the moment.

If we are really trying to abstract the programming level away from the data layer than we should be able to define entities in the EDM as well as their relationships entirely. It would seem that triggers and foreign key contraints are not necessary at the database level (despite how preferable they might be). Is this an option currently?

Thanks

... Sorry, it appears that I posted this to the wrong forum. It should have been in the ADO.NET Orcas forum. My apologies.

Referential integrity constraints on indexed views

Hi
I was wondering whether we can create referential integrity constraints on
indexed views in SQL Server 2000. We are trying to create a data model and
would like to know whether we can enforce constraints on indexed views,
otherwise we may have to go for tables.
Please inform.
Thanks
BobBob,
Not that I'm aware of - never seen anyone add a constraint to a
view(indexed). Would probably have to handle this at the table level with
constraints or triggers.
HTH
Jerry
"Bob" <Bob@.discussions.microsoft.com> wrote in message
news:B911616E-39CC-4879-B485-58ED9E951E23@.microsoft.com...
> Hi
> I was wondering whether we can create referential integrity constraints on
> indexed views in SQL Server 2000. We are trying to create a data model and
> would like to know whether we can enforce constraints on indexed views,
> otherwise we may have to go for tables.
> Please inform.
> Thanks
> Bob|||The indexed view ultimately gets it data from the underlying tables. So if
they have the proper constraints the view will never see incorrect data.
Andrew J. Kelly SQL MVP
"Bob" <Bob@.discussions.microsoft.com> wrote in message
news:B911616E-39CC-4879-B485-58ED9E951E23@.microsoft.com...
> Hi
> I was wondering whether we can create referential integrity constraints on
> indexed views in SQL Server 2000. We are trying to create a data model and
> would like to know whether we can enforce constraints on indexed views,
> otherwise we may have to go for tables.
> Please inform.
> Thanks
> Bob

Referential integrity constraints on indexed views

Hi
I was wondering whether we can create referential integrity constraints on
indexed views in SQL Server 2000. We are trying to create a data model and
would like to know whether we can enforce constraints on indexed views,
otherwise we may have to go for tables.
Please inform.
Thanks
BobBob,
Not that I'm aware of - never seen anyone add a constraint to a
view(indexed). Would probably have to handle this at the table level with
constraints or triggers.
HTH
Jerry
"Bob" <Bob@.discussions.microsoft.com> wrote in message
news:B911616E-39CC-4879-B485-58ED9E951E23@.microsoft.com...
> Hi
> I was wondering whether we can create referential integrity constraints on
> indexed views in SQL Server 2000. We are trying to create a data model and
> would like to know whether we can enforce constraints on indexed views,
> otherwise we may have to go for tables.
> Please inform.
> Thanks
> Bob|||The indexed view ultimately gets it data from the underlying tables. So if
they have the proper constraints the view will never see incorrect data.
--
Andrew J. Kelly SQL MVP
"Bob" <Bob@.discussions.microsoft.com> wrote in message
news:B911616E-39CC-4879-B485-58ED9E951E23@.microsoft.com...
> Hi
> I was wondering whether we can create referential integrity constraints on
> indexed views in SQL Server 2000. We are trying to create a data model and
> would like to know whether we can enforce constraints on indexed views,
> otherwise we may have to go for tables.
> Please inform.
> Thanks
> Bob

Referential integrity constraints on indexed views

Hi
I was wondering whether we can create referential integrity constraints on
indexed views in SQL Server 2000. We are trying to create a data model and
would like to know whether we can enforce constraints on indexed views,
otherwise we may have to go for tables.
Please inform.
Thanks
Bob
Bob,
Not that I'm aware of - never seen anyone add a constraint to a
view(indexed). Would probably have to handle this at the table level with
constraints or triggers.
HTH
Jerry
"Bob" <Bob@.discussions.microsoft.com> wrote in message
news:B911616E-39CC-4879-B485-58ED9E951E23@.microsoft.com...
> Hi
> I was wondering whether we can create referential integrity constraints on
> indexed views in SQL Server 2000. We are trying to create a data model and
> would like to know whether we can enforce constraints on indexed views,
> otherwise we may have to go for tables.
> Please inform.
> Thanks
> Bob
|||The indexed view ultimately gets it data from the underlying tables. So if
they have the proper constraints the view will never see incorrect data.
Andrew J. Kelly SQL MVP
"Bob" <Bob@.discussions.microsoft.com> wrote in message
news:B911616E-39CC-4879-B485-58ED9E951E23@.microsoft.com...
> Hi
> I was wondering whether we can create referential integrity constraints on
> indexed views in SQL Server 2000. We are trying to create a data model and
> would like to know whether we can enforce constraints on indexed views,
> otherwise we may have to go for tables.
> Please inform.
> Thanks
> Bob
sql

Referential Integrity constraints

Dear Sir,
Yesterday during an Interview...i have faced some problem. I would like to
clearify that NN (NOT NULL), ND (NOT DUPLICATE) AND NC(NOT CHANGE)
constraints work ...when we define a Primary Key on any Table column. If,
Yes( as i hope) then how and what's the meaning of this NC. Can You Plz. giv
e
me briefly explain and can we use this in ORACLE .> ...me briefly explain and can we use this in ORACLE .
This is a SQL Server forum. You probably get (better) help in an Oracle foru
m.
In SQL Server, defining a PK doesn't prohibit you to change the value of the
PK column for one or
several rows.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Sanjeev Kumar Sinha" <Sanjeev Kumar Sinha@.discussions.microsoft.com> wrote
in message
news:E7240299-73E3-4C56-891D-66F4CB533174@.microsoft.com...
> Dear Sir,
> Yesterday during an Interview...i have faced some problem. I would like to
> clearify that NN (NOT NULL), ND (NOT DUPLICATE) AND NC(NOT CHANGE)
> constraints work ...when we define a Primary Key on any Table column. If,
> Yes( as i hope) then how and what's the meaning of this NC. Can You Plz. g
ive
> me briefly explain and can we use this in ORACLE .
>
>|||Yeah, well now I would like it to :)
----
Louis Davidson - drsql@.hotmail.com
SQL Server MVP
Compass Technology Management - www.compass.net
Pro SQL Server 2000 Database Design -
http://www.apress.com/book/bookDisplay.html?bID=266
Blog - http://spaces.msn.com/members/drsql/
Note: Please reply to the newsgroups only unless you are interested in
consulting services. All other replies may be ignored :)
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in
message news:OHOkklxHFHA.156@.TK2MSFTNGP10.phx.gbl...
> This is a SQL Server forum. You probably get (better) help in an Oracle
> forum.
> In SQL Server, defining a PK doesn't prohibit you to change the value of
> the PK column for one or several rows.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Sanjeev Kumar Sinha" <Sanjeev Kumar Sinha@.discussions.microsoft.com>
> wrote in message
> news:E7240299-73E3-4C56-891D-66F4CB533174@.microsoft.com...
>|||You have to talk to the ANSI SQL committee about that, Louis. :-)
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
http://www.sqlug.se/
"Louis Davidson" <dr_dontspamme_sql@.hotmail.com> wrote in message
news:OCdomJ1HFHA.3076@.tk2msftngp13.phx.gbl...
> Yeah, well now I would like it to :)
> --
> ----
--
> Louis Davidson - drsql@.hotmail.com
> SQL Server MVP
> Compass Technology Management - www.compass.net
> Pro SQL Server 2000 Database Design - http://www.apress.com/book/bookDisp...r />
l?bID=266
> Blog - http://spaces.msn.com/members/drsql/
> Note: Please reply to the newsgroups only unless you are interested in con
sulting services. All
> other replies may be ignored :)
> "Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote i
n message
> news:OHOkklxHFHA.156@.TK2MSFTNGP10.phx.gbl...

Referential Integrity - Which Column violates this?

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!

CyherusDo you have any ddl that's behind the VB application? Can you match it with the values you want to insert?|||nope, I am basically connecting to the SQL server via odbc.. and using INSERT INTO queries to add records as I read from a text file..
Since the SQL Server is able to throw me an error description that says which table and column name violates the RI, I thought I would be able to manage this with codes. That is create the primary record in the primary table (affected table) and resume to insert the record in the foreign table again..

Cyherus|||It should be done with sp, not with FE-based action queries.|||The text of the error message (in the errors collection) will tell you which foreign key caused the problem. The code is the same for them all, so it only tells you that a foreign key was the problem.

-PatP|||If you do it in sp you can customize the way errors are returned to the client. And of course Errors (rdoErrors) collection should be looped to retrieve ALL the errors that came from the server.|||Alright.. as per your advise.. I am now performing these actions on the BE via sp.
now, I am using both return value, out parameters and capture @.@.ERROR.
Issue is that the system it prompting me before I can capture the errors returned.. sp example:

ALTER PROCEDURE dbo.sp_insert_bl
(
@.AAA varchar(12),
@.BBB int,
)
AS
DECLARE @.err int

SET NOCOUNT ON
BEGIN TRAN
INSERT INTO dbo.Table ([AAA], [BBB])
VALUES (@.AAA, @.BBB)
SELECT @.err = @.@.ERROR
IF @.err <> 0
BEGIN
ROLLBACK TRAN
RETURN @.err
END
ELSE
BEGIN
SELECT @.blid = SCOPE_IDENTITY()
COMMIT TRAN
RETURN 0
END

oh yes, using ado to execute exec the sp
cmd.parameter.........
cmd.execute
cmd.parameter("return value")

do you suggest using RAISERROR?|||Of course, so that you can interrogate Errors collection. How else were you planning to see the errors?

Referential Integrity - Sequel Server 7.0

Hi,

i wrote the following trigger to enforce referential integrity:

CREATE TRIGGER [RefIntegrity] ON [Erf] <- Master table
FOR UPDATE AS

if update(ErfNo) or update(Township) <- Primary keys in master
begin
Update ErfPlan <- Child table
Set ErfPlan.ErfNo = i.ErfNo , ErfPlan.Township = i.Township
From ErfPlan a, Inserted i, Deleted d
Where a.ErfNo = d.ErfNo and a.Township = d.Township
end

i am using VB6.0. When my program updates one of the primary keys i get an error :
Key column information is insufficient or incorrect. Too many
rows were affected by update.

i have designed the ErfPlan table with a RcdID field (Autonumber).

This error ONLY occurs on existing records. If i create a new master and related child record, and update any of the key fields, VB displays no error!the funny thing about the vb error: if i requery the record that had a key value/s changed, i can see that it has been updated (for one-to-one AND one-to-many relationship). what i do not understand is why vb displays the error (Key column information is insufficient or incorrect. Too many rows were affected by update).
this error is only displayed when a master record has a one-to-many relationship, but not in a one-to-one relationship.

Referential Integrity - linking multiple tables to transaction table

I have transaction table where the rows entered into the transaction
can come a result of changes that take place if four different tables.
So the situation is as follows:

Transaction Table
-TranId
-Calc Amount

Table 1 (the amount is inserted into the transaction table)
- Tb1Id
- Tb1Amt

Table 2 (an amount is calculated based on the percentage and inserted
into the transaction table)
-Tbl2Id
-Tb2Percentage

Table 3 (the amount is inserted into the transaction table)
-Tbl3Id
-Tbl3Amut

Table 4 (an amount is calculated based on the percentage and inserted
into the transaction table. )
-Tbl2Id
-Tb2Percentage

How do I create referential integrity between the Transaction table and
the 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.Can you make "Transaction Table" into a view
based on joins between your other 4 tables?

Where does TransID come from?|||Thanks,

Trans ID is generated - identify column.

We thought of using a view. But the when the core object is set to
LIVE, all changes from then on will be tracked as new transactions in
the transaction table. So in essence, you have have a row in Table 1 -
4 that has multiple transactions in the transacation table. We could
add a column to the Transaction Table set it to refer to the Ids of
Table 1 - 4. But we won't be able to use the DBMS contraints to enfore
this. Possibly a middle table to each Table 1 to 4?|||(heyvinay@.gmail.com) writes:
> I have transaction table where the rows entered into the transaction
> can come a result of changes that take place if four different tables.
> So the situation is as follows:
> Transaction Table
> -TranId
> -Calc Amount
> Table 1 (the amount is inserted into the transaction table)
> - Tb1Id
> - Tb1Amt
> Table 2 (an amount is calculated based on the percentage and inserted
> into the transaction table)
> -Tbl2Id
> -Tb2Percentage
> Table 3 (the amount is inserted into the transaction table)
> -Tbl3Id
> -Tbl3Amut
> Table 4 (an amount is calculated based on the percentage and inserted
> into the transaction table. )
> -Tbl2Id
> -Tb2Percentage
> How do I create referential integrity between the Transaction table and
> the 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.

Depends on what you mean with changes, but obviously if you change an
amount in one table and you want that to affect the CalcAmount in the
Transaction table, then you should consider a trigger. For that to
work, the Transaction table need to have one FK column per referencing
table.

Your description was quite brief, and very abstract. It is not at all
impossible that there is a better design, if you can give more meat of
what is behind the various tables.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks.
Well the application we are designing is for Premium calcuation. The
transaction table will store all the premium calcuation breakdowns.
The reference to table 1 - 4 are various elements within the system
that will generated chargeable premiums. Eg. the product selected;
discounts applied to the customer; specific endorsements; Payment
menthod discounts etc. Once policy is live, and changes to the source
tables (eg product, discount amount) etc or even the cancellation of
the policy will raise NEW records in the transaction tables.

We can manage all this from code directly to ensure all is in sync, but
I prefer to apply referential integrity managed by the DBMS.

You wrote: "For that to work, the Transaction table need to have one FK
column per referencing table. " - does MS SQL allow null values for
foreign key constraints?

Thanks|||(heyvinay@.gmail.com) writes:
> We can manage all this from code directly to ensure all is in sync, but
> I prefer to apply referential integrity managed by the DBMS.

Referential integrity is about the integrity of - references. That is,
if the Orders table has a FK constraint to table Customers, you cannot
add an Order for a non-existing customer, and you cannot delete a customer
that has an order.

As I understood it, you want one data in one table be the result of data
in other tables. This cannot be achieved with referential integrity. You
can use views, and under some circumstances you can materialise a view.

> You wrote: "For that to work, the Transaction table need to have one FK
> column per referencing table. " - does MS SQL allow null values for
> foreign key constraints?

Yes. For instance, in a Customers table, you may have Citizen column
table that has a foreign-key constraint to the Countries table. But
this column must be nullable, since some people stateless. Not talking
of juridical persons, who normally are not citizens.

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Off the top of my head, two fundamental ways.

Insert into the 4 tables, and have triggers on those tables for insert,
update, and delete that add rows to the trans table.

Two. utilize standardized stored procedures you use to add/edit/update
the 4 tables. Inside the stored procedures, do a begin trans/ commit
around the changes and the trans table. In this way, you can pretty
much ensure that it will keep up.

The stored procedure has the advantage of allowing more business logic
around changes. You can validate data changes external to the app.
However, you MUST enforce that all changes to the 4 tables MUST uses
the specified stored procedures.

The Triggers have the advantage of "simplicity." Again though,. you are
somewhat limited in what logic you can use.

Two comments you didn't ask for. Be very stingy with indexes on the
trans table. I'm not saying ot have none, BUT don't have a lot of
indexes. And the indexes you do have should be fairly unique. Trans
tables get very large very fast, and they really slow everything down
in a sneaky insidious sort of way in a few years.

Secondly, it can be hard to get the :"right" infomration into the trans
table. As a test to see whether you have all data you need, manually
try to take each trans record, and recreate the final data results. In
a perfect world, your trans table will allow a picture of exactly what
changed when and how, allowing hte final results to be seen.
For a final test, just go ahead and write the program that will read
the trans data and recreate teh table. This is almost never trivial,
but almost always worthwhile.
-dougsql

Referential Integrity - Countries & States/Provinces

I have a Country table with (surprise!) countries, and a Locale table
with states, territories, provinces, etc. I also have another table,
Port, that usually contains Country information but only occasionally
contains Locale information.
My question is, how do I set up the foreign keys maintain referential
integrity for Locale data but still allow for NULLs?
The following seems to fail whenever I have NULLs for the Country
and/or Locale of a Port:
CREATE TABLE Country
(
CountryID nchar(2) NOT NULL PRIMARY KEY,
Country nvarchar(50) NOT NULL
)
CREATE TABLE Locale
(
CountryID nchar(2) NOT NULL REFERENCES Country (CountryID),
LocaleID nvarchar(3) NOT NULL,
Locale nvarchar(100) NOT NULL,
PRIMARY KEY (CountryID, LocaleID)
)
CREATE TABLE Port
(
PortID smallint NOT NULL PRIMARY KEY,
Port nvarchar(100) NOT NULL,
SeaID tinyint NOT NULL REFERENCES Sea (SeaID),
CountryID nchar(2) NULL, --sometimes NULL!!!
LocaleID nvarchar(3) NULL, --often NULL!!!
FOREIGN KEY (CountryID, LocaleID) REFERENCES Locale (CountryID,
LocaleID)
)
Thanks!
-DanLook up the nested sets model and buidl a hierarchy of geography.
Also, ISO country codes are CHAR(3). The trick will be in having a
node type in the locations table and so constraints on the leaf nodes.|||"Dan Manes" <danthman@.cox.net> wrote in message
news:1148083925.869411.11720@.y43g2000cwc.googlegroups.com...
>I have a Country table with (surprise!) countries, and a Locale table
> with states, territories, provinces, etc. I also have another table,
> Port, that usually contains Country information but only occasionally
> contains Locale information.
> My question is, how do I set up the foreign keys maintain referential
> integrity for Locale data but still allow for NULLs?
> The following seems to fail whenever I have NULLs for the Country
> and/or Locale of a Port:
> CREATE TABLE Country
> (
> CountryID nchar(2) NOT NULL PRIMARY KEY,
> Country nvarchar(50) NOT NULL
> )
> CREATE TABLE Locale
> (
> CountryID nchar(2) NOT NULL REFERENCES Country (CountryID),
> LocaleID nvarchar(3) NOT NULL,
> Locale nvarchar(100) NOT NULL,
> PRIMARY KEY (CountryID, LocaleID)
> )
> CREATE TABLE Port
> (
> PortID smallint NOT NULL PRIMARY KEY,
> Port nvarchar(100) NOT NULL,
> SeaID tinyint NOT NULL REFERENCES Sea (SeaID),
> CountryID nchar(2) NULL, --sometimes NULL!!!
> LocaleID nvarchar(3) NULL, --often NULL!!!
> FOREIGN KEY (CountryID, LocaleID) REFERENCES Locale (CountryID,
> LocaleID)
> )
>
Doesn't fail for me:
CREATE TABLE Country
(
CountryID nchar(2) NOT NULL PRIMARY KEY,
Country nvarchar(50) NOT NULL
)
CREATE TABLE Locale
(
CountryID nchar(2) NOT NULL REFERENCES Country (CountryID),
LocaleID nvarchar(3) NOT NULL,
Locale nvarchar(100) NOT NULL,
PRIMARY KEY (CountryID, LocaleID)
)
CREATE TABLE Port
(
PortID smallint NOT NULL PRIMARY KEY,
Port nvarchar(100) NOT NULL,
SeaID tinyint NOT NULL, -- REFERENCES Sea (SeaID),
CountryID nchar(2) NULL, --sometimes NULL!!!
LocaleID nvarchar(3) NULL, --often NULL!!!
FOREIGN KEY (CountryID, LocaleID) REFERENCES Locale (CountryID,
LocaleID)
)
go
insert into country values (1,'usa')
insert into locale values (1,'tx','Texas')
insert into port values (1,'Port Arthur',0,1,'tx')
insert into port values (2,'Houston',0,1,null)
insert into port values (3,'Dallas',0,null,null)
David|||Thanks, David. You're right. My problem was that what I thought were
NULLs in my source data table turned out to be blanks--not the same
thing. Once I replaced them with NULLs, everything was fine.
As for CELKO's comment about ISO Country codes being CHAR(3), there's
both a 2- and 3-character ISO standard. My example just happened to
have the 2-character version.
-Dan|||Go with the 3; the 2 is about to be deprecated becuase we just have too
many countries declaring themselves.|||If only it were that simple :) My real Country table actually has five
different code columns (including 2- *and* 3-digit ISO) because users
will be getting their country code data from several different
sources/databases, all of which use their own codes. Of course, some of
these source databases have country codes for entities the ISO doesn't
even consider countries.
The result, a big messy normalization problem. Don't you just love when
people ignore standards?
Anyway, even though it seems unlikely we'll go from 243 to 676
countries anytime soon, the 3-digit codes also have the advantage of
being more human readable. E.g., with two characters, Canada = CA and
China = CN; with three, Canada = CAN and China = CHN.
-Dan|||> Go with the 3; the 2 is about to be deprecated becuase we just have too
> many countries declaring themselves.
Looks pretty current to me:
http://www.iso.org/iso/en/prods-ser...n1.
html
Can you post your source that states the 2 code is going to be depreciated?
It will cause absolute confusion over here because travelling on the content
you need to have a sticker with your country code on your car and to my
knowledge Great Britian is still GB.
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1148150829.923946.28160@.u72g2000cwu.googlegroups.com...
> Go with the 3; the 2 is about to be deprecated becuase we just have too
> many countries declaring themselves.
>|||Some stickers are 1,2 or 3 characters
I = Italy
F = France
NL = the Netherlands
SLO =Slovenia
I don't think those follow any ISO standards
Denis the SQL Menace
http://sqlservercode.blogspot.com/|||Makes matters worse, I wonder what standard us Europeans use then for that?
The only useful thing I found was from the US CIA site:
http://www.cia.gov/cia/publications...appendix-d.html and
there is no mention of 2 code being depreciated, to make matters even more
interesting ISO 3166 has 3 versions, 2 letter, 3 letter and 3 digit!
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"SQL Menace" <denis.gobo@.gmail.com> wrote in message
news:1148222151.073946.222330@.i40g2000cwc.googlegroups.com...
> Some stickers are 1,2 or 3 characters
> I = Italy
> F = France
> NL = the Netherlands
> SLO =Slovenia
> I don't think those follow any ISO standards
>
> Denis the SQL Menace
> http://sqlservercode.blogspot.com/
>|||On Sun, 21 May 2006 17:48:38 +0100, Tony Rogerson wrote:

> to make matters even more
>interesting ISO 3166 has 3 versions, 2 letter, 3 letter and 3 digit!
"The nice thing about standards is that there are so many of them"
-- Unknown
Hugo Kornelis, SQL Server MVP