I have the following scenario. Let's say I have 3 tables:
IDs are integers and primary key with identity(1,1).
Clients (ID (pk), Name)
Orders (ID (pk), ClientID (fk), Date)
OrderDetails (ID (pk), OrderID (fk), Product, Quantity, Price)
Let's say I accidentally deleted all records from those 3 tables, but I have a DB backup. The question is how do I reinsert those deleted records from backed up DB into the current DB?
I know I can simply "set identity_insert on" and use "insert into", but is a web application and it must stay alive and there are inserts from users going on.
If I insert all Clients back, their ID will be different and Orders(ClientID) cannot refers to that anymore. So on with Orders/OrderDetails tables.
I need some way to update the foreign key ids with new ones. How can I do that?
Some kind of temp tables to keep records of old IDs and new IDs?
Hope that I made my question clear :)
If it were me, I'd:
Determine which rows are in your backup that aren't in your live database
Insert the rows from your backup into your live database with a value of -1 * identity value. For instance, if the row was in the backup with a identity value of 1234, you'd insert it into your live database with an identity value of -1234. This goes not only for identity values, but for any rows that reference those values (i.e. foreign keys).
Related
I am new to SQL server and am wanting to make sure I am using best practices. What I am doing is creating 7 tables.
(Transaction,Customer,Business,Vehicle,Seller,Lien,Mailto)
Transaction is my main table where it creates a TransactionID. Then in the other 6 tables I will also have a TransactionID column so I can link them all together.
In the other 6 tables they each have there own ID as well.
For example
(CustomerID, BusinessID, VehicleID, SellerID, LienID, MailtoID)
My question is in my transaction table do I have to list all of those IDs or does having just the TransactionID allow them all to connect.
Transaction Table 1 Example
ID
Type
DateTime
Transaction Table 2 Example
ID
Type
CustomerID
BusinessID
VehicleID
MailtoID
SellerID
LienID
DateTime
(For the transaction ID I am wanting it to be created and then automatically fill the same in for the other tables as those fields are submitted using foreign keys I believe)
Any help on this would be greatly appreciated!!
do I have to list all of those IDs- NO!.
having just the "TransactionID" allow them all to connect.
Hello I have a scenario where I have multiple SQL databases, and a tool on a central database which connects to each user table on each database and builds a dataset.
The issue happens when say a user from one database is migrated to another. When the tool runs it encounters an issue because the user_id is a guid pk, and since users have been migrated across databases the dataset will end up having duplicate private keys in the final dataset.
My question, if I want to regenerate the user id guid for some user,
I of course have to also update all of the connecting foreign keys. Is
there a command in MS SQL to regenerate the GUID and also do so for
all connecting relationships?
ON UPDATE CASCADE is what you want, but you need to define it in the foreign key relationship ahead of time.
CREATE TABLE User (UserID UNIQUEIDENTIFIER, UserName varchar(30), ... )
CREATE TABLE UserData (DataID UNIQUEIDENTIFIER, UserID UNIQUEIDENTIIFER, ...)
ALTER TABLE UserData
ADD CONSTRAINT FK_UserData_UserID (UserID) REFERENCES User(UserID)
ON UPDATE CASCADE;
Old version
I have a Person table and the table Company.
both tables have a column Id (Identity)
Table Company have Ids of 1 to 165
In the table Person have Ids 1 until 2029
New Version
In the new version of the system, was created a table Entity.
This table contains the records of the Companies and People
The Company and Person tables will be maintained, referring to the Entity table.
The Id in table Entity will be the same in Company or Person table
Question
Both tables have multiple relationships with other tables.
Table Entity (as well as others) has a column ID (identity).
The problem is that the Id were repeated when the two tables together (It was to be expected).
How to import without losing relationships?
Attempts
I thought of changing the value of Ids in Company table, starts from 2030.
Thus the Ids would not duplicate when joining the two tables.
But this creates another questions.
How to do this without losing existing relationships?
How to change the Id of a row in the table and this is reflected in all tables which it relates?
I would like to do this using only DDL (SQL Server)
I thought of changing the value of Ids in Company table, starts from 2030. Thus the Ids would not duplicate when joining the two tables.
Create foreign key constraints on the Person table to all related tables (or alter the existing foreign key constraints) with ON UPDATE CASCADE. Then update the Person table and change the values if the id columns - these changes will cascade to the related tables.
To stop further problems, maybe change the identity columns in Person and Company to something like identity( 1000, 3 ) and identity (1001, 3) respectively.
However, I think the best idea is to have a different EntityID column in the Entity table, unrelated to PersonID and CompanyID. The Entity table would also have a column called AltEntityID or BusinessKey that contains the id from the other table and that does not have a unique constraint or a foreign key constraint.
And if you make small modification to your attempt - add new column, say newId, to Company and to Person to manage relation with Entity and leave id columns as is. Why this is the simpliest way? Because new columns shouldnot be identity columns, from one side. From the other side, you can leave all logic of relating other tables with Company and Person intact.
I have created a form in admin panel with various fields. Now the fields here doesn't belong to one single table. On the save, I want some values go into one particular table while others to go into some other table. I am able to show up the data using joins but don't know how to save them back.
Lets say, I have a tblUser with fields:
tblUser
- user_id INT(11) Auto Increment
- username VARCHAR(15)
- store_id SMALLINT(5)
- bank_id INT(11)
Here, store_id and bank_id have foreign key constraints to auto-increment id's of tblcore_store (id, store_name) and tblBanks (id, bank_name, bank_acc) respectively.
Now the fields in the form are:
Username
Store Id
Store Name
Bank Name
Bank Account
When, admin click save I want the data of form to go into their respective tables and also having their references in store_id and bank_id.
First you have to insert data into tblcore_store and tblbanks then you can find the ids by table status or fetching last record from both of table.
after getting both ids now you can insert data to tblUser
you can follow the below steps in any framework
Start new transaction
Insert data into 1st table
Get last insert id
Insert data into 2nd table using last insert id from point above
Close transaction
Return transaction status or anything you might need from this model function
Don’t forget to use a database that is capable of using transactions, otherwise this does nothing.
I have a table, Contacts, with a primary key of ContactID, which is an identity column. I have another table, Person, with a primary key of PersonID that is a foreign key to ContactID. When I insert a record into Person, I would like PersonID to pull the corresponding identity from ContactID in Contact.
In Access, I simply make a query that references both tables, and it will fill in the foreign key column with the corresponding value in the identity (autonumber) column.
SELECT Person.PersonID, Person.FirstName, Person.MiddleName, Person.LastName, Contact.ContactID, Contact.EmailAddress, Contact.PhoneNumber
FROM (Contact INNER JOIN Person ON Contact.ContactID = Person.PersonID);
How can we achieve this in SQLServer 2008 R2? I have been programming triggers to update the keys, but it seems like there ought to be a better way.
Thank you very much for your assistance.
When you insert to the first table, you use the OUTPUT clause to pull the identity value and then you can use it to insert to the child table.
You can also use scope_identity() to do the same thing, but OUTPUT is the preferred method. Do not under any circumstances use ##Identity as it often will give incorrect results and mess up your data integrity.
Look up how to use them in Books Online.