TechieGirlinCali
TechieGirlinCali

Reputation: 1

How can I move a column over in SQL Server Management Studio?

I forgot to add the IMPORT_DETAILLANDNBR column when I initially created my table. I have to place this column next to the IMPORT_LANDNBR column in my table, but the system automatically places the IMPORT_DETAILLANDNBR column to the end of the table. How can I fix this? Here's what I tried: Right clicking on table and clicking the Design tab, but when I move the column in Design, it moves, but it doesn't stay. It reverts back by moving back to the end of the table.

Upvotes: 0

Views: 322

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88851

The SSMS Table Designer can do this if you really need to change the column order of a table. When you save the change SSMS will generate a change script that creates a new table, copies all the data, drops the old table and renames the new table. EG:

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_TEST_TABLE
    (
    COLLECT_DATA_SEQ int NOT NULL,
    COLUMN2 varchar(36) NOT NULL,
    COLUMN3 varchar(20) NOT NULL,
    COLUMN4 varchar(20) NOT NULL,
    COLUMN5 tinyint NULL,
    COLUMN6 datetime NOT NULL,
    COLUMN7 datetime NULL,
    COLUMN15 datetime NULL,
    COLUMN8 varchar(10) NOT NULL,
    COLUMN9 tinyint NOT NULL,
    COLUMN10 tinyint NOT NULL,
    COLUMN11 tinyint NULL,
    COLUMN12 tinyint NOT NULL,
    COLUMN13 varchar(36) NOT NULL,
    COLUMN14 tinyint NOT NULL,
    COLUMN16 char(8) NULL,
    COLUMN18 char(8) NULL,
    COLUMN17 datetime NULL
    )  ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_TEST_TABLE SET (LOCK_ESCALATION = TABLE)
GO
IF EXISTS(SELECT * FROM dbo.TEST_TABLE)
     EXEC('INSERT INTO dbo.Tmp_TEST_TABLE (COLLECT_DATA_SEQ, COLUMN2, COLUMN3, COLUMN4, COLUMN5, COLUMN6, COLUMN7, COLUMN15, COLUMN8, COLUMN9, COLUMN10, COLUMN11, COLUMN12, COLUMN13, COLUMN14, COLUMN16, COLUMN18, COLUMN17)
        SELECT COLLECT_DATA_SEQ, COLUMN2, COLUMN3, COLUMN4, COLUMN5, COLUMN6, COLUMN7, COLUMN15, COLUMN8, COLUMN9, COLUMN10, COLUMN11, COLUMN12, COLUMN13, COLUMN14, COLUMN16, COLUMN18, COLUMN17 FROM dbo.TEST_TABLE WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.TEST_TABLE
GO
EXECUTE sp_rename N'dbo.Tmp_TEST_TABLE', N'TEST_TABLE', 'OBJECT' 
GO
ALTER TABLE dbo.TEST_TABLE ADD CONSTRAINT
    PK_TEST_TABLE PRIMARY KEY CLUSTERED 
    (
    COLLECT_DATA_SEQ
    ) WITH( PAD_INDEX = OFF, FILLFACTOR = 80, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
COMMIT

Upvotes: 2

Related Questions