I working a tutorial where I will learn a lot of new stuff, LINQ being one of them. As a part of this tutorial, there are four tables and foreign keys. My db skills were limited to simple tables and i've nevr done anything where I related tables before. I'm a bit confused about foreign keys and how to set them up. I think I'm setting up right, but I have a doubt. I have a couple of screen caps to show you what where my doubt comes from at:
http://www.noelakins.com/keys.html
What is causing my confusion is that the connecting lines between the Albums and Events table diagrams in my setup seems to point back to the Photos table, and the Photos table seems to point to the Tags table. From the tutorial, the connecting lines seem to be pointing the other direction. Am I setting up the key right, or do I have them backwards?
I'm setting out to learn a lot of stuff in this tutorial, so when I mess it up, i would like to know that it isn't because the foreign keys are wrong.
EDIT:
After doing some googling and some reading and watching, I'm a little less confused about how to set up foreign keys, at least how to do it in VWD. My problem now seems to be understanding the relationships. In the tutorial example, the Tags table has a FK on the PhotoID field, which matches the primary key (PhotoID) in the Photos table. Now, does this mean that the Tags table is the parent table and the Photos table the child? If this is true, then the other two tables must be child tables of the Photos table. At least that how I think this should work. The issue that I'm having with this is trying to understand how a cascade delete would work. Is the foreign key relationship a one way or both way relationship? For example, if I have made a foreign key on the AlbumID field of the Photos table, where the primary key table is Albums, PK is AlbumID and the foreign key table is Photos, then, if I do a cascade delete of a particular photo, does it delete the album too? That wouldn't make sense. Foreign keys and cascade deletes must be one way, right?
Thanks
I received the error below upon saving when I was trying to create a foreign key in a table using relationships in "table designer" of sql server 2005 management studio. This process has been successful for other tables. What might be the problem?
Thanks
Code Snippet
- Unable to create relationship 'FK_SAMPLE_GRID'. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_SAMPLE_GRID". The conflict occurred in database "acquire", table "dbo.GRID", column 'GRIDNAME'.
I've always created database tables with one Primary Key that increments by one for each new record. I'm working on a database that was built by someone else now that has a lot of defined foreign key relationships (under Tables > specific table > Keys). How helpful is it to define these Keys? I assume it helps make the database more efficient but is it necessary if you're working with small databases?
I'm using SQL Server 2005 Management Studio. I've created several Foreign Key Relationships using Database Diagrams. Now I'm trying to edit the constraints on the relationships, but when I right click on the relationship, the only option available is "Delete Relationships from Database". But I am not able to edit the relationship. Does anyone know how to do this?
I have 2 tables Publication and Advertisment_Codes. I want to update the publication_code in both tables where country_id=1 and publication_code='A'. However, it gives me an error because of foreign key relationship. I tried first updating in Advertisment_Codes and then in Publication table but it didn't work. I tried the other way round but also it didn't work. How can I update the publication code? Thanks
GO ALTER TABLE [dbo].[Advertisment_Codes] WITH CHECK ADD CONSTRAINT [FK_Advertisment_Codes_Countries] FOREIGN KEY([Country_id]) REFERENCES [dbo].[Countries] ([Country_id]) GO ALTER TABLE [dbo].[Advertisment_Codes] CHECK CONSTRAINT [FK_Advertisment_Codes_Countries] GO ALTER TABLE [dbo].[Advertisment_Codes] WITH CHECK ADD CONSTRAINT [FK_Advertisment_Codes_Publications] FOREIGN KEY([Country_id], [Publication_code]) REFERENCES [dbo].[Publications] ([Country_id], [Publication_code]) GO ALTER TABLE [dbo].[Advertisment_Codes] CHECK CONSTRAINT [FK_Advertisment_Codes_Publications]
GO ALTER TABLE [dbo].[Publications] WITH CHECK ADD CONSTRAINT [FK_Publications_Countries] FOREIGN KEY([Country_id]) REFERENCES [dbo].[Countries] ([Country_id]) GO ALTER TABLE [dbo].[Publications] CHECK CONSTRAINT [FK_Publications_Countries]
Whisky-my beloved dog who died suddenly on the 29/06/06-I miss u so much.
Hey guys this is a SQL Server 2005, .net 2.0 question. I got 3 tables: Job, Times, Employee. The times table is related to Job and Employee by foreign keys. The Times table is pretty much a table where the employee's time logs are kept for a specific job. Since there was a M:M relationship between Job - Employee, I decided to create a Times table in between, and the primary key of this table should actually be the PK of Job and the PK Employee, but I couldn't figure out how to make a PK consisting of two fields. Anyhow, my main question is: How to assign an Employee to a specific job in .net? In other words, what's the best way of retrieving the Job_id and Emp_id and sticking them in the Times table? I was doing a form with a drop down for Emp_id and Job_id, but I don't know how to do the inserts... I'm confused and would appreciate any help.THANKS!
How do I move data from one server and append to the same table structure on a second server and preserve the foreign key relationships. In other words TableB.TableA_ID references TableA.ID. The IDENTITY ID numbers themselves will change but they must continue to match up on the destination server the way they did on the source server.
I can do this using procedural programming but that is usually not the way to go.
(btw, this is a cleaned up version of a question I tacked on to another thread)
I have 600 tables in my database, out of which 40 tables are look up value tables. I want generate truncate scripts which truncates all the tables in order of Parent child relationship excluding lookup tables. Is there any way to do this apart from figuring out Parent Child relationship and then writing the truncate statements for each of the table.
For example
EmployeeDetail table references Employee table DepartmentDetail table references Department table Department table references Employee table
I cannot find a good way to view existing Foreigh Key Relationships in SQL Server Management Studio Express. In the Object Explorer, if you click on a table to expand it, you can see a tree view of EVERYTHING about the table (Columns, Keys, Contraints, Triggers, Indexes, Statistics), but NOTHING about Foreign Key Relationships!!
The only way I have found is that you have to open the table in Design mode, then right click, and choose Relationships, and only then can you see what FK Relationships are defined.
You should be able to see the FK Rletaionships in the tree view of the Object Explorer window!
Here is the alter statement that I am trying to use to create a relationship between 2 tables. This does not seem to work on mobile. What am I doing wrong?
ALTER TABLE [SubCategory] CONSTRAINT [FK_SubCategory_Category] FOREIGN KEY([CategoryID]) REFERENCES [Category] ([CategoryID]) ON UPDATE CASCADE ON DELETE CASCADE
I am creating a small piece of software which handles a pre-advice data file, several scanner inputting weights and a supplier weight report.
The pre-advice contains a list of barcodes and details revolving around that barcode, each barcode will be scanned and a weight will be obtained, this will be place in the DB.
Currently my tables can be summarized like this.
Pre-Advice Table Barcode
Lots of other info…
Scanners Table Barcode Date Time Weight
Which device input this information
Suppliers Weight Table Barcode Date Time Weight
Here is the process(es):
1.Pre-advice table populated.
2.When the barcode is scanned and a weight is obtained, a record will be added to the scanners table and this becomes the ‘active’ weight.If there is already an ‘active’ weight against this barcode the user will be asked if they wish to use the ‘active’ weight already in the system or update the ‘active’ weight to the weight they have entered.
3.Then when the supplier weight report is inputted into its table, should the ‘active’ weight be less than the supplier weight, the supplier weight becomes the ‘active’ weight.
At any given time a user can pull a report based on information in the Pre-Advice table, which will need to include the ‘active’ weight for that barcode’s record.
Additionally, no weights should be deleted, I need a fully traceable log of who, what, where & when. I will need to pull reports on the trials of scans so it really is a must to keep these.
Furthermore, if a scanner was to scan the same barcode after the Suppliers weight had been input and the user chooses to replace the weight then, the scanners weight should become the new ‘active’ weight.
I believe I will need to modify my tables to accommodate my needs, however I am not sure exactly what or how to set up what I need.I understand I will need some type of relationship between all of the tables to be able to pull the report on the Pre-Advice table, but I am lost.
how I will need to set up my tables/relationships in order to achieve my requirements?
I have taken on a contract to improve reporting for an old HR database that was developed using FoxPro (Visual FoxPro, I think) with the data stored in SQL Server 2000. There are no foreign keys in SQL Server 2000 so the relationships are maintained inside FoxPro.Is there a way of extracting the relationships from the FoxPro code and generate foreign keys in SQL Server, so that I can do proper design?
I'm looking for a query I can use to alter table relationships. What I want to do in particular, is to set every relationship to cascade on update. Can anyone point me out to a solution? MSDN seems very vague in this subject.
i am trying to set up a customer table with several personal details, including Login and password combined to make a unique identifier. I have made Login the key to the table, but how do i make Login and Password a combined identifier. When i click key in password it just removes the key from Login and places it there. Also how do i include a foreign key in another table ?? Sorry if these questions seem a little lame, I am only a beginner.
INSERT INTO X ...... ( A, B, C )INSERT INTO Y ...... ( J, K, L )If Y has a foreign key M which is the primary key D of X,is there an easy and/or efficient way to have SQL Serverassign D, and tell us what it is so we can add M to thelist for Y ?I know I can select D where A, B, C but I wondered aboutother tricks.--Wes GroleauAlive and Wellhttp://freepages.religions.rootsweb.com/~wgroleau/
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?
Ok, so I open up a book on beginning sql and it discusses relationships.There is something that appears wrong. I am not understanding how the book is describing the one to one relationship. In it's figure, it shows that the same agency can have two different artist id's. But according to it's definition of one to one list can be related from both tables.Can someone explain this further please?Thanks in advance.
How do you show many to many relationships in ASP.NET with datasources? I can retrieve the information from the database easily but I can't manage to save that information into a variable so that i can then call for only information in the M2M table related to the ID Key I want. For example..1 <asp:Label ID="lblTestLabel" Text='<%# DataBinder.Eval(Container.DataItem, "title_id") %>' Runat="server" /> 2 3 <script language="VB" runat="server"> 4 sub Page_Load(sender as Object, e as EventArgs) 5 Dim lblTitleID As Label = Repeater1.FindControl("lblTestLabel") 6 Response.Write(lblTitleID.text) 7 End Sub 8 </script>
When I try to run this script it dosn't work and I get the error: System.NullReferenceException: Object reference not set to an instance of an object. For line 6 of the code above. Is there a way to just retrieve information from a datasource without storing information into a label first? PS: I use sqldatasource tags to retrieve information like:1 <asp:SqlDataSource ID="DataSet1" runat="server" 2 ConnectionString="Driver={MySQL ODBC 3.51 Driver};server=localhost;database=;user=;pwd=;option=3;" 3 ProviderName="System.Data.Odbc" 4 SelectCommand="Select * from titles order by title_id"> 5 </asp:SqlDataSource>
Can someone help me sort something out. Suppose we have two tables in a database.One is named Person, and one is named Birthday. Is this a many to many relationshipor a 1 to many relationship? Person has many birthdays. Example. Joe Schmoe has a birthday for every year of his life. birthday(7/11/1976) has many People (Many people have a birthday on 7/11/1976.
Is there any easy way of getting all the relationships for the tables in aSQL server db? I've looked through Google and the Books online but I'm barely scratching the surface on the systables. I know I can go to each individual table and get the dependencies or even print out the diagram through Enterprise Manager but I really don't want to have to type out all the primary/foreign keys for 100+ tables. Any help on getting this data either through a 3rd party software or querying the systables would be great.
We have a table with approximately 150 colums and 2/3 of them are bit datatypes. We do not expect much activity on this table. Does it make sense to separate it into a few tables instead of 1 with one-to-one relationships? Will the join(s) significantly slow down our web application? Thank you
My hosting servers have "myLittleAdmin" installed. I am new to ms sql I have some experience with Access but I have never set up Relationships inside the database server. I have always just relied on my application logic to call the relations. What is the benefit to setting up relationships in sql, if any?
Hey, I have SQL Sever Enterpise Manager. I am new at this company and I need to know the relationships between ALL the tables. Is there anywhere I can go to view all the primary keys and the relationships?
Is it possible to have 2 different databases and create relationships inbetween the two? I am thinking about way down the road and the size of the databases and I believe that I need to split my data into multiple databases to keep from running into the size limitations.
Ok, so I open up a book on beginning sql and it discusses relationships. There is something that appears wrong. I am not understanding how the book is describing the one to one relationship. In it's figure, it shows that the same agency can have two different artist id's. But according to it's definition of one to one list can be related from both tables.
I have a really small database in terms of number of objects, but very big in terms of data (possibly millions of records). I always try to design my databases to be in the 3rd normal form (at least I hope they are!), but sometimes (for databases consisting of just a few tables) maintaining M:N relationships looks like an over-bloated approach to me... Let's see an actual example. I have a table like this:
Code SnippetCreate table [Airfares] ( [OriginCity] Char(3) NOT NULL, [DestCity] Char(3) NOT NULL, [FareDate] Datetime Default getdate() NOT NULL, [Price] Decimal(9,2) Default 0 NOT NULL, [PriceChange] Decimal(9,2) Default 0 NOT NULL, [Wrong] Bit Default 0 NOT NULL, Primary Key ([OriginCity],[DestCity],[FareDate]) ) go
Now, at first there also was an Airline nvarchar(50) field, which stored the airline name. But now the client requested to store fares for a few airlines if it's the same price and city pair. This way we can have 3 airlines offering the same price on the same itinerary for example. So I added a dictionary table called Airlines:
Code SnippetCreate table [Airlines] ( [AirlineCode] Char(2) NOT NULL, [Name] Nvarchar(50) NOT NULL, Primary Key ([AirlineCode]) ) go
Now, there are two things I can do. We are obviously dealing with the M:N relationship type here. I can either add another nvarchar column in the first table, like Airlines nvarchar(255) and store something like 'AA,AB,AC' there - those would be airline codes. OR I could do it the proper way and create a cross-reference table which will connect both Airfares and Airlines tables (this will store as many records as there are airlines for that particular itinerary, offerring the same price):
Code SnippetCreate table [AirfareAirlines] ( [AirlineCode] Char(2) NOT NULL, [OriginCity] Char(3) NOT NULL, [DestCity] Char(3) NOT NULL, [FareDate] Datetime Default getdate() NOT NULL, Primary Key ([AirlineCode],[OriginCity],[DestCity],[FareDate]) ) go
But this is starting to look overly complicated, isn't it? The pros of this are I'm going to get real relationships, referential integrity, etc., but cons are more difficult code to query all this. What would you do? Do we really need referential integrity everywhere? Are there times when we're better not using relationships? I have seen many programmers skip referential integrity before, which always made me think they are missing something important in a Relational Database Management System.
Ok - I am still a bit weak on SQL. My understanding of FK relationships in a database are to reinforce the data integrity - Correct? For example, does it make sure that the id given for SiteID does indeed exists. Can it link tables like JOIN in select statements? If not, is there any gains by creating them, such as performance?
So, as you can see, at first it appears that I'm after a LEFT JOIN - meaning that the grandparents don't need to have child records to be returned, but, then it turns out that I need INNER JOINS - to limit grandparents when I choose children.