SQL Regenerate Guid PK - sql-server

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;

Related

Change Primary Key with custom identity seed on existing table SQL Server

I very new in SQL Server it's about 3 months. Now, I am stuck with a problem.
I need to change the primary key on a table with lots of data, about 10000 rows. Some other tables have relationship with this table (FK), but some tables stand alone. i wanna change the primary key and change the start identity seed with i want.
I have browsing in google but still no luck.
Can someone in here give me solution.
Thanks..
1)To DROP a PRIMARY KEY Constraint
ALTER TABLE Persons
DROP CONSTRAINT pk_PersonID
2)Alter table with new primary constarint
ALTER TABLE Persons
ADD PRIMARY KEY (pk_PersonID)

SQL Server : restore from backup but keep ID (identity) references

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).

Is there a way to update primary key Identity specification Increment 1 without dropping Foreign Keys?

I am trying to change a primary key Id to identity to increment 1 on each entry. But the column has been referenced already by other tables. Is there any way to set primary key to auto increment without dropping the foreign keys from other tables?
If the table isn't that large generate script to create an identical table but change the schema it created to:
CREATE TABLE MYTABLE_NEW (
PK INT PRIMARY KEY IDENTITY(1,1),
COL1 TYPEx,
COL2 TYPEx,
COLn
...)
Set your database to single-user mode or make sure no one is in the
database or tables you're changing or change the table you need to
change to READ/ONLY.
Import your data into MYTABLE_NEW from MYTABLE using set IDENTITY_INSERT on
Script your foreign key constraints and save them--in case you need
to back out of your change later and/or re-implement them.
Drop all the constraints from MYTABLE
Rename MYTABLE to MYTABLE_SAV
Rename MYTABLE_NEW to MYTABLE
Run constraint scripts to re-implement constraints on MYTABLE
p.s.
you did ask if there was a way to not drop the foreign key constraints. Here's something to try on your test system. on Step 4 run
ALTER TABLE MYTABLE NOCHECK CONSTRAINT ALL
and on Step 7 ALTER TABLE MYTABLE CHECK CONSTRAINT ALL. I've not tried this myself -- interesting to see if this would actually work on renamed tables.
You can script all this ahead of time on a test SQL Server or even a copy of the database staged on a production server--to make implementation day a no-brainer and gauge your SLAs for any change control procedures for your company.
You can do a similar methodology by deleting the primary key and re-adding it back, but you'll need to have the same data inserted in the new column before you delete the old column. So you'll be deleting and inserting schema and inserting primary key data with this approach. I like to avoid touching a production table if at all possible and having MYTABLE_SAV around in case "anything" unexpected occurs is a comfort to me personally--as I can tell management "the production data was not touched". But some tables are simply too large for this approach to be worthwhile and, also, tastes and methodologies differ largely from DBA to DBA.

SQL Server - ALTER query can create FK relationships, but cannot view them?

I'm stumped on whether I have written the correct syntax to create a foreign key.
I used SQL Server 2012 Express.
If I run a ALTER query to set a foreign key relationship between two table, it works fine, no errors occured. However, if I right-click the table where the FK was created, I don't see any relationships.
This is the ALTER query I have wrote. It creates a relationship between Employers and Employees with EmployerID as a FK.
USE demodemo;
BEGIN TRAN t1
ALTER TABLE Employees
WITH check
ADD CONSTRAINT Employees_EmployerID_FK FOREIGN KEY
(EmployerID) REFERENCES Employers(ID);
GO
The command was executed 'successfully'.
However, if I right click the table, Employees, and select 'Relationships'.
No foreign keys relationships can be seen.
I thought writing the above ALTER query would be the equivalent of creating a FK relationship via the 'Relationships' gui.
Despite having no issues in creating foreign key relationships, I just cannot see them at all.
What could I be doing wrong?
Is my ALTER query correct?
What is the ALTER syntax equivalent to allow me to view the "selected relationships"?
Your DML is missing COMMIT. Also, right click and refresh after executing the SQL
Raj

Visual Studio Data Generation and Many-to-Many

The data generation tool that comes with Visual Studio allows you to populate tables with random/patterned data. As an example, you can tell it to populate an Employees table with 50,000 rows and you can tell it to add 5 address rows to an Addresses table for each Employee row.
I've got a junction table much like the permissions example referenced in this Wikipedia article. Pseudo code below...
create table Users (
UserId int primary key,
Username varchar(50)
)
create table Permissions (
PermissionId int primary key,
Description varchar(50)
)
create table UserPermission (
UserPermissionId int primary key,
UserId int, -- foreign key to Users
PermissionId int -- foreign key to Permissions
)
Is it possible to use Visual Studio's Data Generation tool to populate Users, Permissions, and the associated junction table?
Using the GUI, I am only able to populate one of the two related tables by selecting it from the Related Table dropdown for the junction table.
This is a pretty good tool that allows you enforce foreign key referencial integrity when populating data. Give the trial a try, maybe it will do what you need...
http://www.red-gate.com/products/sql-development/sql-data-generator/

Resources