Is there a quick script I can use in SQL Server to change the ID from int to unique identifier without physically going through and doing it manually. I have contemplated code gen to achieve this, but I would have thought using TSQL would be the quickest if possible that is!
views:
29answers:
2
A:
I assume unique identifier you mean identity. If this is the case here is sample script:
BEGIN TRANSACTION
CREATE TABLE dbo.Tmp_MyTable
(
ID int NOT NULL IDENTITY (1, 1)
) ON [PRIMARY]
GO
SET IDENTITY_INSERT dbo.Tmp_MyTable ON
GO
IF EXISTS(SELECT * FROM dbo.MyTable)
EXEC('INSERT INTO dbo.Tmp_MyTable (ID)
SELECT ID FROM dbo.MyTable TABLOCKX')
GO
SET IDENTITY_INSERT dbo.Tmp_MyTable OFF
GO
DROP TABLE dbo.MyTable
GO
EXECUTE sp_rename N'dbo.Tmp_MyTable', N'MyTable', 'OBJECT'
GO
ALTER TABLE dbo.MyTable ADD CONSTRAINT
PK_MyTable PRIMARY KEY CLUSTERED
(
ID
) ON [PRIMARY]
GO
COMMIT
Dmytrii Nagirniak
2009-08-18 07:46:23
+1
A:
You could do it with a script.
ALTER TABLE x ADD COLUMN y uniqueIdentifier null
GO
UPDATE TABLE x SET y = NEWID() --Or NEWSEQUENTIALID() if its safe
GO
ALTER TABLE x ALTER COLUMN y uniqueIdentifier NOT NULL
GO
ALTER TABLE x DROP CONSTRAINT PK_PrimaryKeyConstraintName
GO
ALTER TABLE x DROP COLUMN PrimaryKeyColumn
GO
ALTER TABLE x ADD CONSTRAINT PK_NewPrimaryKeyConstraint PRIMARY KEY CLUSTERED
(
y ASC
)
GO
Note that this wont deal with your foreign key constraints and will break, if you have foreign key constraints this gets interesting, but I'm sure you can see the pattern.
Spence
2009-08-18 07:48:48
I can defo see why this gets interesting :-) and this is why I thought code gen may raise its extremely useful head!!
REA_ANDREW
2009-08-18 07:50:51
MIght I ask if you're certain you need GUIDs? They are really horrible for your indexing if you can't use sequentialID and usually you could get away with just adding a new int column and making the key the combination of the two...
Spence
2009-08-18 07:54:19
The guid's are for replication purposes. Using guid-comb with NHibernate to overcome the indexing issue! Thanks
REA_ANDREW
2009-08-18 08:21:04