Using SQL Server Express 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).
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.
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.
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,
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
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?
I am Paolo, a 3rd year college student taking up computer science. I am currently doing a project as part of my on the job training but am stumped! Maybe you can help! ;)
software used: Sql Server 2000
The facts: 1. there is a CARS database on server 1 (carId, carDescription) 2. there is an issues and problems tracking database on server 2 (problemId, problemDescription) 3. I am supposed to extend the functionality of the issues and problems tracking database to include the cars. i.e. the database on server 2 should look like: (problemID, problemDescription, carId)
The question: Is there a way i can put a foreign key constraint on server2's carID so that i can only input carIDs which are in the CARS table on server1?
The only way i can think of is to make a new table in server1 and just drag a froeign key relationship in enterprise manager's designer, but my boss doesnt want to keep both information on the same db!
suppose if we do not have FK then what kind of advantage we could not avail. we can fetch data from two table by creating a relation in sql.....then why FK is required.
I have a database column that stores a comma delimited list of foreignkeys. Would someone show me how to do a join using the values from alist stored within a record?For example, a record in tbl_cds.genre_id might have a value of "2,5, 6" corresponding to genre_ids 2 , 5 and 6. I want to jointbl_cds.genre_id to tbl_genre.genre_id using the values in that datafield.It seems I need a loop like this:SELECT * FROM tbl_cdsWHEREBegin Looptbl_cds.genre_id[i] = tbl_genre.genre_idEnd Loop.Would someone give me the correct syntax?Is there an alternative method that would create less overhead?Sorry for such a novice post.
Since most use SQL server, I thought I would post the question here.Is it possible, or is there a product or DBMS that enforces referential integrity across multiple databases and database types? Such as SQL Server, Oracle, etc...Thanks,Zath
What are the possible issues I could run in to having multiple foreign keys in a table. Here is why I ask. I have a db (sql server) that has a participant table, a forum table, and a forum reply table. Every record in the forum reply table is associated with the forum table via a PK-FK relationship w/cascading updates/deletes. The participants who post in these tables are not tied back to the participant table via a PK-FK relationship w/cascading updates/deletes. Should they be?
The problem I ran in to is that one particpant was deleted from the participant table but a post with their partid still existed in the forum or forum reply tables.
My feeling is that anytime a participant is deleted, everything that pertains to them should go too, right? If I am right, what do I have to be careful of if I do that?
I am constructing a db in sql server 2000 that will score cross-country running meets. I have an individual results table that needs to only contain participants that are entered as participants but are specific to a certain race as well. Can I have this table be linked back to TWO other tables via the PK-FK relationship and what issues might I have doing that?
I am having trouble creating multiple foreign keys on a table so that I can set up cascading update and cascading delete from two different primary tables. I am using the diagram to do this but when I try to save the diagram I get the following error.
ODBC error: [Microsoft][ODBC SQL Server Driver][SQL Server]ALTER TABLE statement conflicted with COLUMN FOREIGN KEY constraint 'FK_IndResults_RaceData'. The conflict occurred in database 'VIRA', table 'RaceData', column 'RaceID'.
What would cause this to happen? Is it possible that I have records in the foreign table that do not transfer back to the primary table?
Hi all, I am writing a portion of an app that is of intensely high online eCommerce usage. I have a question about identity columns and locking or not. What I am doing is, I have two tables (normalized), one is OrderDemographics(firstname,lastname,ccum,etc) the other is OrderItems. I have the primary key of OrderDemographics as a column called 'ID' (an Identity Integer that is incrementing). In the OrderItems table, the 'OrderID' column is a foreign key to the OrderDemographics Primary Key column 'ID'. What I have previously done is to insert the demographics into OrderDemographics, then do a 'select top 1 ID from OrderDemographics order by ID DESC' to get that last ID, since you can't tell what it is until you add another row.... The problem is, there's up to 20,000 users/sessions at once and there is a possiblity that in the fraction of a second it takes to select back that ID integer and use it for the initial OrderItems row, some other user might have clicked 'order' a fraction of a second after the first user and created another row in OrderDemographics, thus incrementing the ID column and throwing all the items that Customer #1 orders into Customer #2's order.... How do I lock a SQL table or lock the Application in .NET to handle this problem and keep it from occurring? Thanks, appreciate it.
Hi All,I'm trying to solve this for a few days now and I just can't figure itout...I have three tables set up, I'll simplify them for this question:Table 1: HOTELSColumns: HOTEL_ID, HOTEL_NAMEExmple row: 123 || 'Hotel X'Table 2: SERVICESColumns: SERVICE_ID, SERVICE_NAMEExample rows:1 || 'Breakfast in bed'2 || 'King size bed'Table 3: LINK_HOTELS_SERVICESColumns: FK_HOTEL_ID, FK_SERVICE_ID, SERVICE_VALUEExample rows:123 || 1 || 1123 || 2 || 1In table 3 I link different services to different hotels. In the same tableI set the "value" for the service.The first example row of table 3 means something like: Hotel X offersBreakfast in bed. In this case 1 stands for TRUEThe second example row of table 3 means: Hotel X offers King size beds(again: 1 stands for TRUE).What I'm struggling with is selecting the hotel ID's which offer multipleservices. To stay in the example: how can I select all hotels whereSERVICE_ID = 1 AND SERVICE_ID = 1. I can't seem to figure out how to doit...I hope anyone can help... Thanks a lot in advance!!!Robert
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?
I'm going through my tables and rewriting them so that I can create relationship-based constraints and create foreign keys among my tables. I didn't have a problem with a few of the tables but I seem to have come across a slightly confusing hiccup.
Here's the query for my Classes table:
Code:
CREATE TABLE Classes ( class_id INT IDENTITY PRIMARY KEY NOT NULL,
This statement runs without problems and I Create the relationship with my Users table just fine, having renamed it to teacher_id. I have a 1:n relationship between users and tables AND an n:m relationship because a user can be a student or a teacher, the difference is one field, user_type, which denotes what type of user a person is. In any case, the relationship that's 1:n from users to classes is that of the teacher instructing the class. The problem exists when I run my query for the intermediary table between the class and the gradebook:
Code:
CREATE TABLE Classes_have_Grades ( class_id INT PRIMARY KEY NOT NULL,
Query Analyzer spits out: Quote: Originally Posted by Query Analyzer There are no primary or candidate keys in the referenced table 'Classes' that match the referencing column list in the foreign key 'Classes_have_gradesFKIndex2'. Now, I know in SQL Server 2000 you can only have one primary key. Does that mean I can have a multi-columned Primary key (which is in fact what I would like) or does that mean that just one field can be a primary key and that a table can have only the one primary key?
In addition, what is a "candidate" key? Will making the other fields "Candidate" keys solve my problem?
ALTER TABLE [Students] WITH CHECK ADD CONSTRAINT [FK_Students_Schools] FOREIGN KEY([SchoolId]) REFERENCES [Schools] ([SchoolId])
What kind of index would ensure best performance for INSERTs/UPDATEs, so that SQL Server can most efficiently check the FK constraints? Would it be simply:
CREATE INDEX IX_Students_SchlId ON Students (SchoolId) Or CREATE INDEX IX_Students_SchlId ON Students (SchoolId, StudentId)
In other words, what's best practice for adding an index which best supports a Foreign Key constraint?
Hello!I have a table A with fields id,startdate and other fields. id and startdateare in the primary key.In the table B I want to introduce a Foreign key to field id of table A.Is this possible? If yes, which kind of key I have to build in table A?Thx in advance,Fritz
I have a table called BidItem which has another table calledBidAddendum related to it by foreign key. I have another table calledBidFolder which is related to both BidItem and BidAddendum, based on acolumn called RefId and one called Type, i.e. type 1 is a relationshipto BidItem and type 2 is a relationship to BidAddendum.Is there any way to specify a foreign key that will allow for thedifferent types indicating which table the relationship should existon? Or do I have to have two separate tables with identical columns(and remove the type column) ?? I would prefer not to have multipleidentical tables.
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.
I have no way to test this. If let's say the database has logical integrity errors, will it throw back an error to the Check database integrity object such that, the error arrow (the red line which is the error handler stuff) will be triggered for notification purposes?
what does check database integrity in maintenance plan do.
i heard that the transactional log growth in sql server should be fixed to maximum available disk space and must be monitore the threshold through maintenance plan.how can it be done. please advice me through maintance plan instead of shrinking the log as it is unnecessary IO to the disk.
How often is the check database integrity scheduled. is it daily or weekly.
I have a database hosted that doesnt passes the integrity test. Here is the error it gives : Executing the query "USE [db_cs] failed with the following error: "Could not locate entry in sysdatabases for database 'db_cs'. No entry found with that name. Make sure that the name is entered correctly.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Any idea whats wrong and how I can let the integrity test pass for this db.
I have setup a full maintenance plan on SQL2005. When I run the job, I don't see any error but by loooking at the Log file viewer it appears that Check Database Integrity step failed because :
Alter failed for Server 'LUMONT001'.
Moreover, when I run DBCC CHECKDB from the console I have no error message. Any clue? Thanks, Paul
I searched the forum on this topic and saw the following explanation on Check Database Integrity Task, by DarrenSQLIS.
"The Check Database integrity task will fail if the DB has a problem. The task fails; the details are raised in the error event and dumped to the log etc. You can use on Failure precedence constraints or an OnError event handler to capture that failure and do something if you wish."
Here is the link to the quote above. http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2290253&SiteID=1
I would like to continue this discussion on this new thread to help my understanding.
I understand that this command does dbcc checkdb( ) command on a specified server for the databases you want to check. And if a database has a problem the task will fail and raise an OnError event. DarrenSQLIS goes on to say that the error is dumped to a log. What log is this? Where do I specifiy the location of this log?
As per the advice given by somebody i set ldf initial log size as 29 gb and restricted the growth and set the autogrowth to 500 mb i did not run and shrink ldf command on daily basis. this is the advice given by another dba.
then he suggested to create a maintenance plan to check database integrity check. whick will check the disk space threshold.
i did not understand how will the maintenance plan check the disk space and give an alert. where should i check the alert for this maintenance plan. secondly how can i stop my database log file to deliver a message that my disk is full.
please suggest me a best method. where i am wrong , how should i handle the situation without the dba monitoring. and our system has lot of batches running for every minute.