How to merge primary key DB tables - sql-server

The design of both tables is exactly the same.
DB1.dbo.SomeTable
[Index][Private Key]
[data1]
[data2]
[data3]
DB2.dbo.SomeTable
[Index][Private Key]
[data1]
[data2]
[data3]
However, the index is a private key that increases by 1.
I merge DB1 and DB2 tables, but I need to create a table by automatically increasing the private key by 1 so that the private key does not overlap.

Related

how to define relations between many tables while I have multiple columns primary key?

I have one table its name is (DataInfo) that contains data information "this table will be linked to every table in the database"
DataID,DataName
and I have two another tables
first one is :
DataID,CurrencyID,CurrencyName
Second one is :
DataID,TransID,TransDec,TransAmount,CurrencyID
my question is how to define the relations between these tables ?
DataID will be the foreign key for two tables besides "DataInfo". For first table CurrencyID will be the primary key and DataID will be foreign key. For second table TransID will be the primary key and DataID and CurrencyID will be the foreign key. Both table need not have a tuple of columns as their primary key as TransID will be unique for every transaction and so will be CurrencyID for each currency

Swap the foreign key in two tables in Oracle database

I have two table in Oracle TABLE_A and TABLE_B both table have around 20000 to 30000 records.
The records in TABLE_B are linked to the records in TABLE_A via a foreign key -
(TABLE_B contains the Primary Key of TABLE_A)
I need to swap the Foreign key. i.e.
I want that now TABLE_A should contain the Primary key of TABLE_B.
(It is a functional requirement - because of some validations at the front end, the updates on these tables in the current form of database implementation are not possible.)
Also, while doing this, I want that the records that were linked from (TABLE_B -> TABLE_A) still remain linked.
Now through the new Foreign key (TABLE_A -> TABLE_B).
The FOREIGN KEY can be moved easily, by a couple of ALTER TABLE commands, the main problem area is keeping the data and re-linking it correctly.
The most obvious way to do this would involve taking backups of the entire tables and then creating new scripts to re-insert the updated data in both table.
Is there any faster way to do this without any chances of error.
Assuming the following structure:
TABLE_A (a_id [pk], ...)
TABLE_B (b_id [pk], a_id, ...)
unique constraint on TABLE_B (a_id)
referential constraint TABLE_B (a_id) -> TABLE_A (a_id)
You can do something like this, assuming your system can handle a short outage:
ALTER TABLE TABLE_A ADD (b_id NUMBER);
MERGE INTO TABLE_A t USING
(SELECT b_id, a_id FROM TABLE_B) s
ON (t.a_id = s.a_id)
WHEN MATCHED THEN UPDATE
SET t.b_id = s.b_id;
ALTER TABLE TABLE_A ADD CONSTRAINT a_b_fk
FOREIGN KEY (b_id) REFERENCES TABLE_B (b_id);
ALTER TABLE TABLE_B DROP COLUMN a_id;
For only 30K records this should take very little time.
The only bits missing from the above is dropping the old primary key constraint on TABLE_B and adding the new one on TABLE_A(b_id).

How do I model a many-to-many relation in SQL Server?

I need to introduce a many-to-many relationship between two tables, which both have an integer for primary key, in a SQL Server database. How is this best done in T-SQL?
Consider the following two example table definitions for which there should be a many-to-many relationship:
CREATE TABLE [dbo].[Authors] (
[Id] INT IDENTITY (1, 1) NOT NULL,
CONSTRAINT [PK_Versions] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Books] (
[Id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
The traditional way is to use an additional many:many (junction) table, which links to both tables:
CREATE TABLE [dbo].[AuthorsBooks] (
-- Optionally, we can give the table its own surrogate PK
[Id] INT IDENTITY(1,1) NOT NULL,
AuthorId INT NOT NULL,
BookId INT NOT NULL,
-- Referential Integrity
FOREIGN KEY(AuthorId) REFERENCES Authors(Id),
FOREIGN KEY(BookId) REFERENCES Books(Id),
-- PK is either the surrogate ...
PRIMARY KEY CLUSTERED ([Id] ASC)
-- ... Or the compound key
-- PRIMARY KEY CLUSTERED (AuthorId, BookId)
);
One moot point is whether you want the compound key AuthorId, BookId to be the Primary Key, or whether to add your own new Surrogate - this is usually a subjective preference.
Some of the points to consider whether going for a compound primary key or a new surrogate key for the Junction table:
Without the surrogate, external tables linking to the junction table would need to store both compound keys (i.e. would need to retain both AuthorId and BookId as foreign keys).
So a new surrogate offers the potential benefit of a narrower primary key, which then means any tables linking to this junction table will have a single, narrower foreign key.
However, with the compound keys, there can be an optimisation benefit that tables can join directly to the underlying Books or Authors tables without first joining to the junction table.
The following diagram hopefully makes the case of the compound key clearer (the middle table Nationality is a junction table of PersonCountry):
Edit
Usage is straightforward - if the link exists in the many:many table, then the relationship is deemed to exist. To test the existence, you 'join through' the link table e.g.
-- Find all books written by AuthorId 1234
SELECT b.*
FROM Books b
INNER JOIN AuthorsBooks ab
ON b.Id = ab.BookId
WHERE ab.AuthorId = 1234;

No foreign key restraints on a temporary table? SQL Server 2008

I know that a a temporary table will only exist for as long as a session of SQL Server is open, but why can't you have foreign key restraints on them?
Imagine this scenario: You create a foreign key relationship from your temp table to a concrete table's key. One of the restrictions on a foreign key relationship is that you cannot delete a row from a key table that is depended upon by your temp table. Now, generally when you create foreign key relationships you know to delete the dependent table rows before deleting the related rows in the key table, but how does a stored procedure or any other call into the database know to delete rows from your temp table? Not only is it impossible to discover spurious foreign key dependencies, other sessions could not reach your temp table even if it could discover the relationship. This leads to spurious failures in delete statements as foreign key constraints restrict the key table for dependent rows.
You can create foreign keys between tables in tempdb. For example, try this:
use tempdb
create table parent
(
parent_key int primary key clustered
)
create table child
(
child_key int primary key clustered,
child_parent_key int
)
alter table child add constraint fk_child_parent foreign key (child_parent_key) references parent(parent_key)
insert into parent(parent_key) select 1
insert into child(child_key, child_parent_key) select 1, 1
insert into child(child_key, child_parent_key) select 2, 2 -- this fails because of the FK constraint
drop table child
drop table parent
Could be because you can't have cross-database foreign key constraints and temp tables technically are created in the TempDB database.
Unless you mean between a temp table and another temp table... but really there's lots of issues you get into when you talk about those kind of constraints on a temp table.

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