SQL Relationship Error - sql

I have a database and for the sake of simplicity, lets say it has two tables. One is Employee and the other is EmployeeType. In the Database diagram i am trying to build a relationship of the two tables but it gives me the following error....
'EmployeeType (HumanResources)' table saved successfully
'Employee (HumanResources)' table
- Unable to create relationship 'FK_Employee_EmployeeType'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_Employee_EmployeeType". The conflict occurred in database "TheDB", table "HumanResources.EmployeeType", column 'iID'.
I don't know what is wrong with it. please help...

Ouch, so many downvotes. At least he bothered to post the error message. As Daniel A. White said above, you likely already have the foreign key you're trying to make. Your tag says you're using SQL Server 2008, so I'm going to assume you Microsoft SQL Server Management Studio. If that is the case, one mistake I used to make (and sometimes still do!), is I go to create a new relationship by right-clicking any of the columns in the Design view of the table I want to make a foreign key, and hit Relationships. In the Foreign Key Relationships menu that appears, I hit "Add" at the bottom, and then expand the "Tables and Columns Specification" section. Then I hit the "..." next to "Tables and Columns Specification," which lets you choose what columns you want to relate.
Now the problem here that I sometimes run into is, if you don't finalize this relationship right here, you're setting yourself up for situations like this. The reason is, is that when you hit "Add" a few steps back, you already created a foreign key on this table. Even if you cancel out and close everything, the table retains that foreign key. If you experimented around with this, you may have already accidentally created the relationship, you just didn't know it then.
I realized how often I made this mistake when I first started, because I looked back at my very first project a year after I began working with SQL Server 2008, and the Foreign Key Relationships are funny, because I have a ton of foreign key entries pointing to no where in every table, where I obviously was just experimenting as I was learning.
Another thing, just to cover some more bases here, is that you mentioned you were doing this in the Database Diagram view. Don't think there's anything wrong with that, but I've found that sometimes doing things via the GUI, it can be kind of flakey. By that, what I mean is, sometimes I will want to make a really small and minor change, but the GUI will tell me that I can't do that kind of change after the table has been made. But then if I just do exactly what I want to do via a typed out query, it runs just fine.
The ultimate test to try to see if you have your desired functionality is to simply try putting in a record that would violate the foreign key restraint. If it goes through, then the relationship isn't there or it's not set up properly. If it fails, then you know you've already got what you want.
I think you got some downvotes because this isn't a very complicated problem/should usually be easily solvable on your own, especially with Google. Since it's not, but you bothered to post anyway, I'm assuming you're somewhat new to this, so I just wanted to throw out my advice as a fellow newbie. Don't let the downvotes get you down, just maybe next time ask a little more concrete question other than "what's wrong?" For instance, "This error seems to be telling me the key already exists. Can anyone tell me how to check and see what relationships already exist? I don't remember making this relationship, how could this have happened?" etc.

A simple answer: you have data in your tables which would break this relationship, so you cannot create the relationship.
In this case, check the Employee table and look for rows where the id for EmployeeType (EmployeeTypeId?) is either NULL or illegal (not to be found in the EmployeeType table). Fix these rows and the relationship will save OK.

Related

Need advice on repeating a table primary key on multiple linked tables as foreign key

I'm looking for a second opinion from maybe someone with more experience with SQL.
So I have a database that looks like this :
Company has multiple Clients which has multiple Projects which has multiple Tasks, etc.
In my application a user is assigned a company and cannot query information that isn't tied to it. So whenever a user tries to retrieve Client/Project/Task/Punch I need to make sure that my query contains a Where clause that looks like WHERE companyID=[user's company id]. This add a lot of joins when I need to fetch Punch since I need to go up the chain to see if the company is the same as the user.
Since a client/project/task/punch will never switch from a company to another one, I was wondering if there's any red flag to add a companyID field in project/task/punch in order to simplify the querying ?
I'm using PostgreSQL
If I understand correctly, what you are buildng is a multitenant system, where your companies are the tenants. If that is the case then there are no red flags - on the contrary, your main concern is to isolate data belonging to different companies in the most efficient and most secure way.
I find this old blog post to be a basic but clear introduction to multitenancy.
The recommended way to go was then, and is today, the third option: one DB, many schemas. I'm no Postgres expert, but I believe it supports that option quite well.

Allow a newly created table to inherit constraints from the parent table

I have recently been allotted development tasks at my job after a couple of years providing customer training/service/support (Yay, long run paying off!) I pointed out to my supervisor and was agreed with that we need to add a couple of tables to implement a new feature in order to stay consistent in the way that our front-side application handles the information in the database.
Currently, information is stored all together in one table until it is approved by an end user to be permanently added to the database. It is possible for the information to be one of three types - Two of the three are special case scenarios that require a second level of finalization from an end user before being put into their final location. For these two that require the second level of finalization, all of the other bits and pieces of information that supplement the primary information are stored in separate tables from the primary piece.
My question is this - These secondary tables where the information temporarily resides before being finalized are basically all foreign keys. I was looking at creating the new set of tables from the existing initial tables - Is there a way during that creation for the new secondary table to inherit the constraints that are coming with the initial table columns?
While both of these particular tables are going to be small ones and I don't mind manually creating the script to add the constraints after the creation of the table, it seems like this would be valuable information to know in the future. I've looked through stack overflow, but all questions that are remotely similar are from a different version of SQL.
Additionally, this would have to work all the way back through SQL Server 2008, as we have not stopped supporting 2008 yet.
If you go into Management Studio, right click on the table and go to "Script Table as >" Then "Create to >" . That will add all the constraints.

MS Access 2007 - After importing tables, recordsets are no longer updateable

We have an in-house program at the company I work for, and inside of MS Access we link all of our tables to our three databases. However; in order to create new routes for students, someone needs an isolated copy of our program to work with that won't impact the actual database.
After deleting the linked tables, importing them all locally, and saving the .mdb I can no longer change values inside of most forms. For example:
A drop down menu with a list of possible route codes for a student will appear. Usually you can select one. You are no longer able to, and in the bottom left hand corner you see "this recordset is not updateable".
I'm a bit new at this, but I can't imagine why importing the tables would break anything. I wouldn't expect any key violations to occur (like I might when linking tables), or anything of that nature. If anyone can point me in the right direction it would be much appreciated! Thanks!
Access can handle a compound primary key on a linked table or view. The important thing, of course, is to make sure you're telling Access the right fields to use. It's common for Access not to get the primary key info when you're linking to a view (perhaps the ODBC driver doesn't pass that info along?), but I bet it can happen with tables too.
Not sure if these pics will help, but hopefully it can point you in the right direction. Here's a linked view, as you can see in this picture:
If you open it in design view, you can see that there are no primary keys:
which means that the table isn't editable (the add new button is greyed out):
So I run this command to tell Access to use a compound primary key on the linked view:
CurrentDb.Execute "Create Unique Index PrimaryKey On View_AssnsWithSorterField([Serial No], AssignmentDate)"
If you open the linked view in design view again, you can see the compound primary key:
and now the add new button appears.
You said that you tried to add a compound primary key but Access wouldn't allow it, which sounds like there's something about the table's data or structure that prevents it from using that key. How about creating an empty copy of the table in the backend database, then try linking to that? If that still doesn't work then maybe there's a unique constraint, or a trigger, or something else on the table that causes Access not to like making it updateable. Conversely, if it links fine and you can add/edit records in the linked blank test table, then it must be data in the real table that's causing the issue.
Sometimes if you cut down a copy of the table into smaller chunks (like maybe just start with the primary key columns alone) and gradually rebuild it piece by piece, you eventually hit on the thing that makes Access not let it be updateable.
One other possibility, of course, is a problem with the driver itself. The ODBC drivers that link to SQLServer and Oracle are good quality and can handle complex primary keys, but I've used junky drivers that link to obscure databases and they couldn't handle complex things like subqueries, union queries, etc, even though you could do those things in the database itself; the driver was only written to handle basic select/insert/update/deletes and that was it.

Dropped and recreated the the table in SQL - Data not being read after that

I am a beginner level programmer who was assigned to update the data content in UI. this UI references a database table so I went ahead and began updating the table as per constraints. I had a backup of the data taken and had the create construct imported as well before running the modification queries on SQL Server Management Studio 2008.
A misleading update statement corrupted the table when it updated the whole database instead of 4 rows and I could not pin point to what data ended up being modified and what remained same. Long story short, I had to delete the records and eventually drop the table and then reconstruct it also. Everything went well, I recreated the schema and inserted the data from the backup and continued querying.
However, the UI which was populating its display section from my table went all blank after the incident and I am at a loss to know where is it exactly that I went wrong. It is a small database and this table was NOT referencing any other table. The permissions look good as it was before. I can't really understand what has gone wrong. Queries work well.
If you have had the patience to read my tediously long narrative till now, can you please tell me what is it that I am missing here ?!
I apologize for the overdrawn description but the context felt more important than the problem statement itself.

sql constraints

Why do i have to drop all constraints (keys in general) before i can drop a table in sql server. I dont understand why this would be necessary if I have permissions to drop the table and the know how to do it why not drop all constraints for me?
Is there some sort of technical or database design reason for this?
Because of referential integrity, you (or someone else) might mistakenly attempt to delete a table that holds supporting information.
Just today, my office found an issue with records missing from a report due to account records being purged without checking for data integrity. Those records now have to be restored...
The idea is, as much as it's a pain to do, the process makes absolutely sure the operation is occurring as intended.