I wanted to add a primary key to an existing table. I think that the best way to do this would be to do a SELECT INTO into a temp table, drop and create the table, and then INSERT INTO the created table from the temp table. Are there any issues that could arise from this?
Is this the best practice?
SET XACT_ABORT ON
--SAVE DATA
SELECT * INTO #TempTable
FROM dbo.OldTable AS tt
-- Drop and Create dbo.OldTable
-- Restore data
INSERT INTO dbo.OldTable (Column1, Column2, Column3)
SELECT
tt.Column1,
tt.Column2,
tt.Column3
FROM #TempTable AS tt
COMMIT TRANSACTION -- roll back in case there are any FK issues
This database is implemented in SQL Server 2008.
1 Answer