Let's say I have tbl1, tbl2, and tbl3, this is what they look like
tbl1
UnitID PK
SomeField varchar
SomeField2 varchar
tbl2
UnitID PK
ServiceID PK
SomeField3 varchar
tbl3
UnitID PK
ChangeID PK
SomeField4 varchar
SO I have three tables in my simple app. Due to some constraints, the data needs to be split up in multiple tables
The user will go to enter a UnitID values in tbl1, then they will add additional data and that data will be stored in tbl2 and tbl3 with the same UnitID and their own corresponding PK's (ServiceID, ChangeID).
WHat I'm looking to see if it can be done is if i delete a value from tbl1, say UnitID=2, am I able to automatically delete all corresponding values from tbl2 and tbl3 with that same UnitID? Or do I have to basically have a delete statement for each table?
I found a doc that is referring to delete foreign key relationships but it shows that it is starting SQL 2016, I'm working in SSMS 2012.
Is something like this possible? The reason why I'm asking is because this is a very simplified view of my tables, I will actually have about 20 tables, and there might be a time where I need to delete that UnitID from every single table in my app. I'm trying to make the code as efficient as possible.
The app is coded with Asp.Net, and VB.NET
I understand that I can simply do
Delete * from tbl1 where UnitID=2
Delete * from tbl2 where UnitID=2
but this seems tedious. Any help will be greatly appreciated. Thanks.
Drop your existing foreign key constraint if you have already created your table relationships and you can add new foreign key constraint with cascade delete.
ALTER TABLE child_table
ADD CONSTRAINT fk_name
FOREIGN KEY (child_col1, child_col2, ... child_col_n)
REFERENCES parent_table (parent_col1, parent_col2, ... parent_col_n)
ON DELETE CASCADE;
If you are going to create new tables then you can have foreign key constraint with Cascade delete.
CREATE TABLE child_table
( parent_col1 INT PRIMARY KEY,
parent_col1 INT NOT NULL,
CONSTRAINT fk_name
FOREIGN KEY (child_col1, child_col2, ... child_col_n)
REFERENCES products (parent_col1, parent_col2, ... parent_col_n)
ON DELETE CASCADE
);
Related
So i am trying to complete finance. Following is the .schema:
sqlite> .schema
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT NOT NULL, hash TEXT NOT NULL, cash NUMERIC NOT NULL DEFAULT 10000.00);
CREATE TABLE sqlite_sequence(name,seq);
CREATE TABLE history(
symbol TEXT, name TEXT, shares INTEGER, price NUMERIC, time DATETIME
);
CREATE UNIQUE INDEX username ON users (username);
When i try to add foriegn key to history table it always return error. Here is my code:
sqlite> ALTER TABLE history ADD COLUMN id INT;
sqlite> ALTER TABLE history ADD FOREIGN KEY(id) REFRENCES users(id);
Parse error: near "FOREIGN": syntax error
ALTER TABLE history ADD FOREIGN KEY(id) REFRENCES users(id);
^--- error here
I think based on what I see in the sqlite docs that the statement should be together with the ADD column:
ALTER TABLE history ADD COLUMN id INTEGER REFERENCES users(id);
But you please check me on this syntax! Another option is to take care of creating the constraint at the same time that you create the table.
CREATE TABLE history(
symbol TEXT,
name TEXT,
shares INTEGER,
price NUMERIC,
time DATETIME,
id INTEGER,
FOREIGN KEY (id)
REFERENCES users (id));
It might not be something you have realized (yet) but every database has its unique flavor of SQL, so despite there being a SQL standard there are often little differences in the syntax of SQL for specific db implementations. So you always have to beware of this when looking up commands for your sql db.
Further detail on Sqlite foreign key constraints can be found here:
https://www.sqlitetutorial.net/sqlite-foreign-key/
I have made a simple relation table. All consist of three tables:
Tables for storing personal data (Table_Person)
Table for storing address data (Table_Address)
Table to store the relationship between Table_Person and Table_Address (Table_PersonAddress).
What I want to ask is can I delete the primary key in Table_PersonAddress so that Table_PersonAddress doesn't have a primary key and all that's left is the personID and addressID?
Below is an example of a database relation that I made:
enter image description here
Assuming you don't have any foreign key constraints setup on the junction table (that is, the third table which just stores relationships between people and their addresses), you could delete a person from the first table, while leaving behind the relationships in the third table. However, just because you could do this, does not mean you would want to. Most of the time, if you remove a person from the first table, you would also want to remove all of his relationships from the third table. One way to do this in SQLite is by adding cascading delete constraints to the third table, when you create it:
CREATE TABLE Table_PersonAddress (
...
CONSTRAINT fk_person
FOREIGN KEY (personID)
REFERENCES Table_Person (ID)
ON DELETE CASCADE
)
You probably would also want to add a similar constraint for the address field in the third table, since removing an address also invalidates all relationships involving that address.
Note that SQLite does not allow a cascading delete constraint to be added to table which already exists. You will have to recreate your tables somehow in order to add these constrains.
You can delete it, but my advice is to set a composite PRIMARY KEY for the 2 columns personID and addressID so each row is guaranteed to be UNIQUE.
PRIMARY KEY (personID, addressID)
and remember that in SQLite you always have the rowid column to use it as an id of the row if needed.
So create the table with this statement:
DROP TABLE IF EXISTS PersonAddress;
CREATE TABLE PersonAddress (
personID INTEGER,
addressID INTEGER,
PRIMARY KEY(personID, addressID),
FOREIGN KEY (personID) REFERENCES Person (personID) ON DELETE CASCADE,
FOREIGN KEY (addressID) REFERENCES Address (addressID) ON DELETE CASCADE
);
One more thing: why did you define personID and addressID as TEXT?
Surely SQLite is not at all strict at data type definitions, but since the columns they reference are INTEGER they also should be INTEGER.
I've created a second table that I want to copy data from a first table to.
table2 has the same structure as table1, only some of it's columns are COLLATE NOCASE. Apart from that and the table names, the tables are identical.
Each table has the PK:
hID INTEGER PRIMARY KEY AUTOINCREMENT
When copying, I get an error on the following query:
INSERT INTO table2 SELECT * FROM table1
The error:
PRIMARY KEY must be unique
I'm assuming the original data is unique, as it's always had the PK.
I want to preserve the original hID's when copying ie I don't want new hID's set for the old data being copied.
In MySQL, I'd normally apply a PK to the second table AFTER copying over the data, but I think that's not allowed in SQLLite.
Can anyone explain the error in my ways?
I am trying to delete a record from one table in my db, but another table has references to this row (foreign keys). So I want to make on delete cascade using SQL Developer in Oracle 11g. How can I do this?
To answer the OP's technical question:
In SQL Developer, you edit the (child) table with the foreign key reference. Select "Constraints" from the treeview on the left and then select the foreign key in question. In the "Referenced Constraint" form there is a drop down named "On Delete". From that drop down, choose "Cascade".
If you are trying to delete rows in a (parent) table and other (child) tables have foreign key references to it, then it will cause the
ORA-02292: integrity constraint (XXXXXX) violated.
TO delete all the child rows whenever a parent record is removed, you specify the "ON DELETE CASCADE" option.
CREATE TABLE Dept_tab (
Deptno NUMBER(3) CONSTRAINT Dept_pkey PRIMARY KEY,
Dname VARCHAR2(15),
Loc VARCHAR2(15),
CONSTRAINT Dname_ukey UNIQUE (Dname, Loc),
CONSTRAINT Loc_check1
CHECK (loc IN ('NEW YORK', 'BOSTON', 'CHICAGO')));
CREATE TABLE Emp_tab (
Empno NUMBER(5) CONSTRAINT Emp_pkey PRIMARY KEY,
Ename VARCHAR2(15) NOT NULL,
Job VARCHAR2(10),
Mgr NUMBER(5) CONSTRAINT Mgr_fkey REFERENCES Emp_tab,
Hiredate DATE,
Sal NUMBER(7,2),
Comm NUMBER(5,2),
Deptno NUMBER(3) NOT NULL
CONSTRAINT dept_fkey REFERENCES Dept_tab ON DELETE CASCADE);
In this case , if a row from the department table is deleted, instead of raising an error which is the default case, it will delete all the employees form the employee table.
This has nothing to do with the tool (SQL Developer)...
I have a bunch of SQLite db files, and I need to merge them into one big db files.
How can I do that?
Added
Based on this, I guess those three commands should merge two db into one.
attach './abc2.db' as toMerge;
insert into test select * from toMerge.test
detach database toMerge
The problem is the db has PRIMARY KEY field, and I got this message - "Error: PRIMARY KEY must be unique".
This is the test table for the db.
CREATE TABLE test (id integer PRIMARY KEY AUTOINCREMENT,value text,goody text)
I'm just thinking off my head here... (and probably after everybody else has moved on, too).
Mapping the primary key to "NULL" should yield the wanted result (no good if you use it as foreign key somewhere else, since the key probably exists, but has different contents)
attach './abc2.db' as toMerge;
insert into test select NULL, value, goody from toMerge.test;
detach database toMerge;
actual test:
sqlite> insert into test select * from toMerge.test;
Error: PRIMARY KEY must be unique
sqlite> insert into test select NULL, value, goody from toMerge.test;
sqlite> detach database toMerge;
I'm not 100% sure, but it seems that I should read all the elements and insert the element (except the PRIMARY KEY) one by one into the new data base.