sql server linked tables - sql

suppose I have three tables (table1, table2, table3) linked to a master table tableM.
I have primary key ID in the tableM and foreign key ID in other tables.
suppose I insert a row in tableM, will other tables get inserted a row automatically? Or do I have to write a sp by my own?
Thanks for any advice!

Rows do not get inserted automatically. You have to insert a row into your master table first, and then insert rows into your FK tables afterwards to avoid a FK constraint error.

No, rows are not inserted automatically. Additionally, the INSERT statement could not possibly include columns from these child tables, so even if a row were inserted automatically it could not include data.
You will need to either write a stored procedure (recommended if these child rows are required by the business logic) or simply insert into tables as necessary.

Related

Deleting rows from multiple tables

I created a query that will delete rows from three tables that has 'Employee'.
When I execute it, it only deletes rows from one table tblEmployeeType. I tried adding Alias of other tables beside DELETE but SQL does not support it. Is there any alternative way of deleting rows from multiple tables? or I forgot some codes on my query or should I just separate delete queries? Thank you.
DELETE a
FROM tblEmployeeType a INNER JOIN
tbl_Selected_AccessType b
ON a.EmpTypeName = b.UserType INNER JOIN
tbl_AccessType_AllFunction c
ON a.EmpTypeName = c.UserType
WHERE a.EmpTypeName = 'Employee'`
INSERT and UPDATE statements can only directly affect one table at a time. If you have foreign keys configured with ON DELETE CASCADE then child records will be deleted along with the parent record. Regardless of using cascade, you should have foreign keys on the table so that your DELETE doesn't leave orphaned child records with broken referential integrity.
Another way to achieve affecting other tables in an INSERT or UPDATE is by using a trigger on the table. This can be desirable when you want to do checks before blindly deleting child records.

Insert Records with Violations in SQL Server

I want to populate 5000 records in the below format to a particular table.
Insert into #Table
(c1,c2,c3,c4,c5)
Values
(1,2,3,4,5),
(2,2,3,4,5),
(3,2,3,4,5),
(4,2,3,4,5),
(5,2,3,4,5)
....
....
Up to 1000 rows
When I try to execute it. I got a foreign Key violation. I know the reason since one of the value did not exist in its corresponding parent table.
There are few records causing this violation. It's very hard to find those violated rows among the 1000 rows so I want to insert at least the valid records to my target table leaving the violated rows as it is for now.
I am not sure how to perform this. Please suggest me any ideas to do this.
If this is a one time thing, then you can do the following:
Drop the FK constraint
ALTER TABLE MyTAble
DROP CONSTRAINT FK_Contstraint
GO
Execute INSERT
Find the records with no matching parent id.
SELECT * FROM MyTable MT WHERE NOT EXISTS (SELECT 1 FROM ParentTable PT WHERE MT.ParentId = PT.ID)
DELETE those records or do something else with them.
Recreate the FK constraint.
Disable the foreign key or fix your data.
Finding the bad data is simple - you can always temporarily insert it into a buffer table and run queries to find which data is missing in the related table.

Incrementing 2 fields after inserting values based on another table?

This is an extension of Insert values into table B based on column from table A?
From the above question, let's say in both the User_Permissions and Users table there's also 2 more columns recorded for audit purposes: a version column and a transaction_version column. When inserting the new row (which is based on a row from the Users table) into the User_Permissions table I need to take the value of the 2 columns in the Users table, increment it by 1 and then insert it into the User_Permissions table.
Is there an easy SQL query to do this? I suspect it'd have to do with another inline select but am unsure of the syntax.
You could use Triggers after insert to perform the needed updates

Delete rows from multiple tables in a database

I want to delete some records from a table based on criteria in another table. How do you delete from one of those tables without removing the records in both table?
I am looking to delete a table which are joined with other tables and the query looks something like this.
DELETE DeletingFromTable
FROM DeletingFromTable
INNER JOIN CriteriaTable ON DeletingFromTable.field_id = CriteriaTable.id
WHERE CriteriaTable.criteria = "value" ;
This should work:
DELETE DeleteFromTable FROM DeleteFromTable AS DT
JOIN CriteriaFromTable AS CT ON DT.SomeId = CT.SomeId
WHERE CT.SomeId=[value]
Your question is not 100% clear on what your issue is, but this query will drop tables 1,2 and 3 at the same time:
DROP TABLE table1,table2,table3
You can only delete data from one table at a time.
To delete from multiple table
Write multiple queries separated by semicolon and execute it at onces like
delete from table1;
delete from table2;
delete from table3;
Or you can write the procedure to do this task.
Please check this thread as well
Drop multiple tables in one shot in mysql
You can use:
DELETE FROM TableName
Which will remove all the data, but if you have any seeded columns, these will not be reset. If you want to DELETE data and reset the seeding of PK's, then use TRUNCATE...
TRUNCATE TABLE TableName
But, you need to consider whether you have other tables that have referential integrity, if this is the case, see this post here SQL Server: How to ignore referential integrity until COMMIT?
EDIT:
Your comment above...
delete query like this DELETE FROM table_name WHERE
some_column=some_value;
...suggests you are looking to delete specific rows?
You can just write a query to DROP the tables like so:
DROP TABLE [TABLE_1]
DROP TABLE [TABLE_2]
DROP TABLE [TABLE_3]
Depending on the tables and any constraints you may have between them, you will need to DROP the tables in the correct order.
If you right click any table (depending on SQL version), you should be able to 'View Dependencies'. If the 3 tables you are planning to DROP are only dependant on each other, you need to DROP the tables with no child dependencies first to avoid it failing.
For example, if you try to delete a parent table where it's primary key is referenced in a child table as a foreign key, the DROP will fail because of this. So deleting the child table with the foreign key first will allow you to subsequently DROP the parent table.
If however, the tables have other dependencies outside the tables you are deleting, you will need to remove the dependencies before this will work.

Copying rows in a database when rows have children

I need to make a copy of a row in a table and also copy all the rows that link to it via its foreign key in other tables. And then copy all the rows that link to these rows.
The problem is when I make a copy of the row the key is going to change. How can I propagate these changes through the relationships between tables?
You can write a stored procedure which implements all the copy logic.
Essentially:
Insert copy row in master table -
store new ID in variable
Insert
copy of each row in child tables,
referencing FK in variable. Store the ID of the child row in variable2
Insert new rows in tables dependent upon the child table, referencing the FK in variable2.
In short, write a stored proc that starts at the top and walks down as many tables as needed.
A bit of a 'hack', but I often add a column 'copy_of_id', so that I can store the old id, and then copy over all rows in dependent tables for the newly created value.
It ain't pretty, but has advantages (human tracebility of what's happening, for instance).
You can also use a helper table for this, of course. Containing old ID and new ID columns. That will not pollute your primary table.
When creating your new "parent row", ##IDENTITY and SCOPE_IDENTITY() will contain the Id of your new header.
Then you can use them to create your "child rows", such as
INSERT INTO parent_table (parent_field1, parentfield2) VALUES('Some stuff', 'Other stuff');
INSERT INTO child_table (parent_id, other_field) VALUES(SCOPE_IDENTITY(), 'Etc.')
Take a look on MSDN for ##IDENTITY and SCOPE_IDENTITY() for code examples.