SSMS SQL - Create table with related columns - sql

I have a DB Diagram with relationships on primary and foreign keys. Then I create a new table in the diagram, with foreign keys to 2 other tables. Example:
Tables in the diagram: Customers, Orders and Status
New table: View (with fk to Customers(CustID), Orders(OrID) and Status(SID))
In view table, I want a column Ordertype which should be a related/linked column to Orders table.
Meaning, that whenever I change a value of Ordertype in my new View table, it gets updated in the Orders table as well.
How can I achieve this? I guess I need sql script that adds such a related column to my view table.
What I have tried:
Relationship Orders(PK) and View(FK) has update property set to "Cascade".
Given same column name and datatype to Ordertype in both tables, Orders and View
But, this doesn't work for me.
Thanks.

Foreign key constraints can't help you to update data. You could try to use DML Trigger.
For example,
CREATE TRIGGER InsertUpdateTrigger ON View
AFTER Insert, Update AS
BEGIN
UPDATE O
SET O.OrderType = I.OrderType
FROM ORDERS O
JOIN INSRTED I on O.orid = I.id(change to your id)
END

Related

SQL. Deleting data from a table, but maintaining the relationship

I work in PostgreSQL
I have two tables. The first is the product and the second is the receipt. They are referenced using a foreign key (the product in the receipt table). I need to delete the product row from the product table, but to keep the reference. I wanted to make it a "virtual table" (product) where the receipt table will reference after deleting information from the main product table.
But I can't figure out how to do it... Can someone tell me or show me how to do this.
You can't have a foreign key relationship to a non-existent row. So, do a soft-delete. That is, add a column to the products table such as is_deleted.
Then don't actually delete the row. Just set the column to true.
It can be helpful to have a view for active products:
create view v_products as
select p.*
from products p
where not is_deleted;
EDIT:
If you want to change the row in the original table, you can use a cascading option on the trigger. Use on delete cascade to remove the row in receipts or on delete set null to set the referencing value to NULL. I'm not a fan of these because you lose the original data.

Delete from 2 tables using INNER JOIN

I have 3 tables.
InvoiceOriginal
Invoice
InvoiceHistory
the invoice table has a foreign key constraint.
Each entry in the invoice table has a corresponding entry in Invoiceoriginal.
The invoiceOriginal table stores the original values of the invoice and invoice table stores the values which have been modified by the user.
this is done to get diferrences at the time of submission.
the SQL I am using is
DELETE i
FROM invoice i
INNER JOIN InvoiceHistory aih
ON i.ClientId = aih.HistoryClientNumber
AND i.invoiceNumber = HistoryInvoiceNumber
however deletion is not possible because of foreign Key constraint.
The table is as under:
Invoice InvoiceOriginal InvoiceHistory
Id FK_InvoiceId ClientId
ClientId ClientId InvoiceNumber
InvoiceNumber
I need to delete the entry in invoice and InvoiceOriginal once there is an entry for that invoice number in InvoiceHistory for the same clientId.
You cannot issue a delete statement against more than one table at a time, you need to have individual delete statements for each of the related tables before deleting the parent record(s)
I'm fairly sure you can't delete from multiple tables with a single statement. I would normally delete the child rows first with one statement and then delete the parent record. You may wish to do this inside a transaction if you might need to roll back on failure.
Alternatively, you could enable CASCADE ON DELETE on the foreign key which would automatically cascade the deletions through the child records if that is something that is suitable for this system.
You can't delete the records from multiple table from a single query. But you have two methods to solve this
Delete all the related records from child or mapping table, and then
delete the Parent / header table record. (Multiple queries required here. Use SQL Transaction for a better control).
Or, Modify your foreign key constraint to ON DELETE CASCADE
Yes, YOU CAN, I did it right now:
DELETE T1,T2 FROM T1
INNER JOIN
T2 ON T2.FIELD = T1.FIELD
WHERE
T1.SOMETHING='SOMETHING'

Tables not showing anything when creating new one

I have problem with SQL .
I am trying to create tables from other tables with foreign keys. The table is created normally without problem but when I'm trying to see the data inside the table there is none of the data inside! Anyone who knows?
-- Here is my table with the foreign keys
CREATE TABLE StaffXCustomersXMeals(
--MealID int FOREIGN KEY REFERENCES Meals(MealID),
--CustomersID int FOREIGN KEY REFERENCES Customers(CustomersID),
--StaffID int FOREIGN KEY REFERENCES Staff(StaffID)
)
You might want to consider reading up on the concept of a SQL View - think of it as a "virtual table based on the result-set of an SQL statement." When you create a view based on the JOIN between multiple tables, it saves your query and you can then select from it like you would a table.
For example, you might have the following:
CREATE VIEW StaffCustomerMeals
AS
SELECT
m.MealID,
c.CustomersID,
s.StaffID
FROM
Meals m
LEFT JOIN
Customers c ON
m.SomeIDThatMeansThisCustomer = c.CustomersID
LEFT JOIN
Staff s ON
m.SomeIDThatMeansAStaffMember = s.StaffID
You need to define these relationships in accordance with your own schema - it's your homework assignment, so do your best to figure it out. A couple more questions to consider:
Does a meal always have both a customer and a staff member, or are they customers who might happen to be staff members?
Should you include other information besides the IDs (e.g., CustomerName, StaffMemberDepartment, MealPrice, PurchaseDate)
You didn't enter any data. You only said that whatever data entered must reference the other tables. So you cannot enter invalid meals for instance.
You need INSERT statments to fill the table with whatever data you need.

easiest way to map ids during database refactoring

i have a number of tables with a column called OrderId. I have just done a refactoring and i want to get rid of the Order table and i have a new table called Transaction. I want all tables that have an OrderId column to now have a TransactionId column
This is complete. I now need to populate the transactionId column. I have a mapping today between orderId and transactionId so i wanted to see the quickest way i can go populate that new transactionId column (should i do this through code, through a SQL query, etc ??)
So i have the transationId column in the Order Table so i can do a join.
I want a query that says something like this (pseudo SQL)
update childTable CT
set transactionId = MapFromOrderId(CT.OrderId)
any suggestions?
I would do it in SQL code:
UPDATE MT
SET
transaction_id = MAP.transaction_id
FROM
My_Table MT
INNER JOIN My_Map MAP ON
MAP.order_id = MT.order_id
Then check to make sure that every row was mapped:
SELECT
*
FROM
My_Table
WHERE
transaction_id IS NULL
The process is usually:
Make sure the database is backed up
Addtransctionid to each child table.
Populate based on a join to the
mapping table (you did store the
mappings between orderid and
transactionid in a table?)
Make sure you have no blank values.
Then you create the FK for
transactions, drop the fk to the
Order table and then drop the orderid
column.
Then move to the next table and
repeat.
Test to make sure everything worked
properly
Definitely I'd do this in a script so it will be easy to port to prod after dev and QA testing.
On prod you need to do this while the database is in single user mode to prevent new orders from being added as the process transitions.

problem creating a simple relationship in SQL Server 2005

I am using the database diagram to simply drag one column in a table to another to associate them and then trying to save it. i have done this a million times in the past with no problems. Both of the data types are the same, uniqueidentifier.
Here is the error I get:
'Customer ' table saved successfully
'CustomerOrder ' table
- Unable to create relationship 'FK_CustomerOrder_Customer'.
The
ALTER TABLE statement conflicted with
the FOREIGN KEY constraint
"FK_CustomerOrder_Customer". The
conflict occurred in database
"mydatabase", table "Customer", column
'CustomerID'.
Not sure how to trouble shoot this.
It means that there's a CustomerID in the CustomerOrder which can not be found in the Customer table.
Run this query inside SQL Server Management Studio separately:
SELECT *
FROM CustomerOrder co
WHERE NOT EXISTS (SELECT * FROM Customer c WHERE c.CustomerID = co.CustomerID)
and that should tell you what the "bad" Customer Order records are.
Are there customer orders with customer id's that don't exist in the customer table?