Combine the Data of two SQL databases to one - sql

I have two SQL databases with the same schema. Both have different Data but are using the same primary keys. I want to add the Data from one database to the second one, but all solution I found just update the rows with the same primary keys and dont attach them at the end.
Anyone has a solution?

If your primary key column is an ID field that uses an auto-incrementing sequence (if not, then how would you choose a different primary key for overlapping records anyway?), you should just be able to insert the records from the first schema, excluding the ID in your select query.
For example:
Table Schema:
ID INT(10)
Name VARCHAR(20)
Desc TEXT
SQL
INSERT INTO schema2.table (Name, Desc)
SELECT Name, Desc
FROM schema1.table

Related

Creating unique primary key to ignore duplicates

I have a main large table which I have had to put into 3rd normal form and into smaller tables (with primary and foreign keys linking them). The table is about renting books.
I have a customer table which I need to create a primary key for. In the main large table there are duplicates of the customer_id, as the table as a whole is for renting the books, so one customer may have more than one renting.
The table I am currently trying to add a primary key for will not have any nulls or duplicates, however i am unsure how to create the primary key for this without the error- unsure how to make it unique.
CREATE TABLE customer AS
SELECT cust_id, country_id, name, address, postcode
FROM BOOKS
WHERE cust_id != 0;
ALTER TABLE customer
ADD PRIMARY KEY (cust_id);
Is anyone able to help me in how to create the primary key on my customer table, but just taking each unique cust_id from the main table.
In SQL Server the straightforward way to add unique keys is to use IDENTITY. Identity fields are integer fields that auto populate successive values by a specified start value and interval. If you don't specify the interval it will start at 1 and increase the value by 1 each time a value is assigned.
While it's usually done when creating a table, you can do it in your ALTER TABLE step, and it will assign values when added to an existing table. I've explicitly specified the start value and interval that matches the default to show the syntax :
ALTER TABLE customer
ADD cust_id int not null PRIMARY KEY IDENTITY(1,1)

Sql combine value of two columns as primary key

I have a SQL server table on which I insert account wise data. Same account number should not be repeated on the same day but can be repeated if the date changes.
The customer retrieves the data based on the date and account number.
In short the date + account number is unique and should not be duplicate.
As both are different fields should I concatenate both and create a third field as primary key or there is option of having a primary key on the merge value.
Please guide with the optimum way.
You can create a composite primary key. When you create the table, you can do this sort of thing in SQL Server;
CREATE TABLE TableName (
Field1 varchar(20),
Field2 INT,
PRIMARY KEY (Field1, Field2))
Take a look at this question which helps with each flavour of SQL
How can I define a composite primary key in SQL?
PLEASE HAVE A LOOK, IT WILL CLEAR MOST OF THE DOUBTS !
We can state 2 or more columns combined as a primary key.
In that case every column included in primary key will be called : Composite Key
And mind you Composite keys can never be null !!
Now, first let me show you how to make 2 or more columns as primary key.
create table table_name ( col1 type, col2 type, primary key(col1, col2));
The benefit is :
col1 has value (X) and col2 has value (Y) then no other row can have col1 as (X) and col2 as (Y).
col1, col2 must have some values, they can't be null !!
HOPE THIS HELPS !
Not at all. Just use a primary key constraint:
alter table t add constraint pk_accountnumber_date primary key (accountnumber, date)
You can also include this in the create table statement.
I might suggest, however, that you use an auto-incrementing/identity/serial primary key -- a unique number for each row. Then declare the account number/date combination as a unique key. I prefer such synthetic primary keys for several reasons:
They make it easy to refer to a row in foreign key relationships.
They show the insert order into the table, so you can readily see the last inserted rows.
They make it simple to identify a single row for updates and deletes.
They hide the "id" information of the row from referring tables and applications.
The alternative is to have a PK which is an autoincrementing number and then put a unique unique index on the natural key. In this way uniqueness is preserved but you have the fastest possible joining to any child tables. If the table will not ever have child tables, the composite PK is a good idea. If there will be many child tables, this is could be a better choice.

Select row query given table name and primary key in Oracle?

So after googling this simple question, I could have not find an answer anywhere. I only have very basic database knowledge, and I need a query in Oracle to properly select a row given a table name and a primary key. Most examples I have found all find rows based of a row number or rowID (is that the same as primary key?).
Any help on this would be greatly appreciated.
Do you have the primary key column and the value you want to query? Where or what exactly did you search for? This is a very basic SELECT statement in any relational database:
SELECT *
FROM table_name
WHERE primary_key_column = primary_key_value
Unless, of course, I didn't understand the question.
A primary key is a unique identifier for a row in a table. Each row will have a primary key that is different from all other rows. This key can be one value, such as a rowID, or it can be a composite value (multiple columns used as a primary key because there may not be a need for an extra column only to store a rowID).
#tilley31 above shows a great example of how to search for a specific row in a table. If the primary key was composite;
SELECT *
FROM table_name
WHERE primary_key_column1 = primary_key_value1
AND primary_key_column2 = primary_key_value2
ROWID is a pseudocolumn that returns the address of a row and is usually unique, exception being where more than one table is stored in a same cluster then those tables rows can share the same rowid. ROWID is implicitly given by the oracle to rows.
Primary key uniquely identifies a row at a table level and is created by the user who created the table.
Getting the ROWID of a Row
SELECT ROWID,FIELDNAME FROM ABC;
Getting the PRIMARY Key of a table
SELECT * FROM USER_CONSTRAINTS WHERE TABLE_NAME='YOUR_TABLENAME'
AND CONSTRAINT_TYPE='P';
I guess you are intent to dynamically choose table and where clauses in query (?)
If this is what you want to do then answer is No. Its not possible just through query. You could achieve it through pl/sql. and if you must have this as a query consider using a table function like below -
SELECT * FROM TABLE(func('TABLE_NAME','WHERE_CONDITION'))
Check out this link: https://oracle-base.com/articles/misc/pipelined-table-functions
Again this requires you to have preset output columns (COLUMN1, COLUMN2 etc). You will not be able to select exact column names from table.
Overall this is going to be messy.

inserting data in two tables Simultaneously

I have two table in my database , Position and Reservation that ID of Position is foreign key in Reservation. I want to insert data in reservation table but before this , data must be inserted to position table simultaneously . how can i do this??? can I use triggers or store procedure???
I assume your tables look like this:
position: int id
reservation: int id, int position_id
First you've got to have a look at your foreign key position_id. If it has a NOT NULL constraint, you won't be able to create a reservation entry without before creating a position entry.
Using "normal" SQL queries, it's not possible to insert data into two tables with a single query.
Why do you need it to happen within one query? Because of data integrity? Then use transactions!

Create a one to many relationship using SQL Server

How do you create a one to many relationship using SQL Server?
Define two tables (example A and B), with their own primary key
Define a column in Table A as having a Foreign key relationship based on the primary key of Table B
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b: Name of the foreign key constraint, must be unique to the database
b_id: Name of column in Table A you are creating the foreign key relationship on
b: Name of table, in this case b
id: Name of column in Table B
This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.
You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:
In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.
I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.
You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:
The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.
Having this constraint will ensure that no Order records can exist without an accompanying Customer record.
To effectively query a database like this, you might want to read up on JOINs.
This is how I usually do it (sql server).
Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4".
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.
As you can see the second insert into the detail fails because of the foreign key.
Here's a good weblink that shows various syntax for defining FK during table creation or after.
http://www.1keydata.com/sql/sql-foreign-key.html
If you are not using SSMS then here is the syntax:
ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)
http://infogoal.com/sql/sql-add-foreignkey.htm
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId.
If this is not what you are looking for, please elaborate your question.