Connecting the tables in a database - sql-server

I have created a simple database in SQL Server Express which consists of three tables: Inventory, Customers, Orders.
I try to connect them in db diagram forcing the primary keys of Inventory and Customers (CarID and CustID) as foreign keys to Orders. However, when I try to save the diagram, I receive an error that does not allow me to save the diagram and link the tables.
The error indicates:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"FK_Orders_Inventory". The conflict occurred in database "AutoLot",
table "dbo.Inventory", column 'CarID'.
FK_Orders_Inventory is the connection between Inventory and Orders. What could be a potential cause of the error?

The data currently in the table is probably not conforming to the constraints you have defined.
Make sure the data is consistent with the constraints before adding them.
In this case, one of the foreign keys you are defining fails because the column you are defining it on (in the Inventory table) contains values that do not exist on the referenced column (CarId) in the foreign table.

You have a CarID value in the child table that does not exist in the parent table.

Related

How to keep foreign tables imported via foreign data wrapper in Postgres up to date with underlying table?

I am wondering how foreign data in Postgres are updated. I understand that the FDW makes a connection to the remote database to access the tables, and the foreign tables don't take up physical memory in the database. It is the equivalent of making a select statement to the the underlying tables.
I have some tables in Database A that I have imported as foreign tables into database B. I am using the foreign Tables in Database B to create materialized views.
I am running these commands in Database B:
IMPORT FOREIGN SCHEMA completed LIMIT TO (tb1,tbl2)
FROM SERVER db_data_pipeline
INTO public;
COMMIT;
CREATE MV1 AS SELECT * FROM TB1;
My tables in database A are updated through a drop and recreate process. I have two questions regarding how foreign data are synchronized:
Since my tables in database A are updated through a drop and recreate, are the foreign tables in Database B also updated automatically? is there a scenario where the foreign data becomes 'stale'? Would I have to re-import foreign tables to keep them up to date?
I've read that the foreign table definition does not change when the underlying table changes. For example, a column added in the underlying table will not be reflected in the foreign table. However, since my underlying table is never updated directly and dropped and recreated instead, do I have to worry about this issue?
Ad 1:
When you query tb1 in database B, PostgreSQL composes a query, connects to database A and runs the query. If the table in database A has been dropped and re-created, this query will access the new table, since it goes by the table name. There is no need to drop and re-create the foreign tables. The data in the foreign tables will never be stale, but the data in the materialized views can of course become stale.
Ad 2:
Yes, you have to worry about that. A change in the table definition on database A will not change the foreign table in database B. So if you add a bew column in database A, it will not show up in the foreign table in database B. If you drop a column in the table in database A, querying the foreign table may cause an error, since the query could access the missing column. You have to modify or re-create the foreign table to deal with metadata changes.

Cannot create a relation between two tables with three primary keys

I recently used Microsoft SQL Server Migration Assistant for Oracle to convert an Oracle database to a SQL Server database through a two-pass approach.
There is are two tables, BILL_INFO and BILL_INFO_DETAIL, that are supposed to have a master-detail relation through composite PK. However, when I try to create that relation, I get this error:
'BILL_INFO' table saved successfully 'BILL_INFO_DETAIL' table
- Unable to create relationship 'FK_BILL_INFO_DETAIL_BILL_INFO'. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
"FK_BILL_INFO_DETAIL_BILL_INFO". The conflict occurred in database
"MyDatabase", table "dbo.BILL_INFO".
The database is plagued with bad data. So I did a basic search in the detail table to find BILL_NUMBER, PAY_MODE_ID, and CASHIER_ID that may not exist in master (one by one) and found two records when searching on BILL_NUMBER. I fixed them and also verified that PAY_MODE_ID and CASHIER_ID were in order.
Still, I cannot create the relation. Same error. Now I wonder if the Tuple is invalid between tables. How do I find a composite key that exists only in details table?
You could check for non-existing values using:
SELECT bill_number, pay_mode_id, cashier_id
FROM Bill_Info_Detail
EXCEPT
SELECT bill_number, pay_mode_id, cashier_id
FROM Bill_Info;
-- and then fix missing data
When using composite key, you need to check all columns as tuple.

How to insert Master/Detail record in SQL Server?

I have three tables: Employee, Emp_Address and Emp_AddressDetail.
Employee table is master and Emp_Address is detail.
Emp_Address is master and Emp_AddressDetail is detail.
I want to copy all rows from a table to another table.
How can I do it?
If I understand your question correct you want to insert data from one table to another? If so, you should have a look at the INTO statement. http://msdn.microsoft.com/en-us/library/ms188029.aspx
SELECT * INTO dbo.OneTable FROM Production.AnotherTable
If the tables have foreign keys defined, and those foreign key definitions need to be set on the new database, than you need to take a look at the data diagrams, and identify any tables that do not have foreign key columns. In your case the copy order will be Employee, Emp_Address, Emp_AddressDetail
If you do not have explicit SQL Server maintained foreign keys, or if the foreign keys are not set on the target database, you can just copy the data in any order you like.
Note that it's entirely possible to paint yourself into a corner, e.g. if there was field in the Employee table called PrimaryAddress that would be a foreign key to the Emp_Address table.

Introducing FOREIGN KEY constraint 'c_name' on table 't_name' may cause cycles or multiple cascade paths

I have a database table called Lesson:
columns: [LessonID, LessonNumber, Description] ...plus some other columns
I have another table called Lesson_ScoreBasedSelection:
columns: [LessonID,NextLessonID_1,NextLessonID_2,NextLessonID_3]
When a lesson is completed, its LessonID is looked up in the Lesson_ScoreBasedSelection table to get the three possible next lessons, each of which are associated with a particular range of scores. If the score was 0-33, the LessonID stored in NextLessonID_1 would be used. If the score was 34-66, the LessonID stored in NextLessonID_2 would be used, and so on.
I want to constrain all the columns in the Lesson_ScoreBasedSelection table with foreign keys referencing the LessonID column in the lesson table, since every value in the Lesson_ScoreBasedSelection table must have an entry in the LessonID column of the Lesson table. I also want cascade updates turned on, so that if a LessonID changes in the Lesson table, all references to it in the Lesson_ScoreBasedSelection table get updated.
This particular cascade update seems like a very straightforward, one-way update, but when I try to apply a foreign key constraint to each field in the Lesson_ScoreBasedSelection table referencing the LessonID field in the Lesson table, I get the error:
Introducing FOREIGN KEY constraint 'c_name' on table 'Lesson_ScoreBasedSelection' may cause cycles or multiple cascade paths.
Can anyone explain why I'm getting this error or how I can achieve the constraints and cascading updating I described?
You can't have more than one cascading RI link to a single table in any given linked table. Microsoft explains this:
You receive this error message because
in SQL Server, a table cannot appear
more than one time in a list of all
the cascading referential actions that
are started by either a DELETE or an
UPDATE statement. For example, the
tree of cascading referential actions
must only have one path to a
particular table on the cascading
referential actions tree.
Given the SQL Server constraint on this, why don't you solve this problem by creating a table with SelectionID (PK), LessonID, Next_LessonID, QualifyingScore as the columns. Use a constraint to ensure LessonID and QualifyingScore are unique.
In the QualifyingScore column, I'd use a tinyint, and make it 0, 1, or 2. That, or you could do a QualifyingMinScore and QualifyingMaxScore column so you could say,
SELECT * FROM NextLesson
WHERE LessonID = #MyLesson
AND QualifyingMinScore <= #MyScore
AND #MyScore <= QualifyingMaxScore
Cheers,
Eric

Modifying an existing column to a foreign key

I have an oracle db which has no Foreign Keys, all table relations are handled by the software. For example, table Customer with columns Customer.customercode, Customer.Name where customercode is the primary key and table Order with columns Order.ordercode (PK), Order.customercode where customercode has no foreign key constraint. So far the application handles all transactions and takes care of all the table relations so that the data are consistent. I need to change this to a proper relational DB implementation, so I need to modify Order.customercode to be a FK from table Customer. Any sqlplus statement to do this without losing my data?
In Oracle, creating a foreign key would never lose any data, but it will fail if the data doesn't correspond to the new constraint. Assuming your data is OK, you can use an alter table statement:
ALTER TABLE order
ADD CONSTRAINT order_customer_fk FOREIGN KEY (customercode)
REFERENCES customer(customercode)

Resources