Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering SQL table to add column

I currently have a table with four columns - i wanted to add a fifth column but having some trouble.

I open the table in sql server studio management 2008 and i added the column info like so:

CREATE TABLE [dbo].[Case]
(
    CaseId                  UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    CaseNumber              NVARCHAR(50) NOT NULL,
    CourtId                 INT NOT NULL,
    DateOpened              DATETIME NOT NULL,
) 

my addition:

CREATE TABLE [dbo].[Case]
(
    CaseId                  UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    CaseNumber              NVARCHAR(50) NOT NULL,
    CaseName                NVARCHAR(50),
    CourtId                 INT NOT NULL,
    DateOpened              DATETIME NOT NULL,
)

After adding CaseName column, i tried executing the table in Management Studio but i got the error message "There is already an object named 'Case' in the database." I tried saving and then building my database hoping that the column will be added but that wasn't successful. I tried a New Query and writing the 'Alter table "case" add CaseName nvarchar(50) but again without luck. It shows that the file is changed with the new column because i saved it but after building my overall database it isn't making any changes. Any helpful tips will be great.

like image 519
Masriyah Avatar asked Mar 20 '26 17:03

Masriyah


2 Answers

You want to ALTER, as follows:

ALTER TABLE [dbo].[Case] ADD CaseName NVARCHAR(50)

Better yet, you can check for the existance of the column first:

if not exists (SELECT 1 FROM sysobjects INNER JOIN syscolumns ON 
    sysobjects.id = syscolumns.id 
    WHERE sysobjects.name = N'Case' AND syscolumns.name = N'CaseName')
ALTER TABLE [dbo].[Case] ADD CaseName NVARCHAR(50)
like image 99
LittleBobbyTables - Au Revoir Avatar answered Mar 23 '26 08:03

LittleBobbyTables - Au Revoir


you should try this

 ALTER TABLE [dbo].[Case]

    ADD CaseName NVARCHAR(50)

You are trying to create another table Case but one already exists that's why you have an error. When you want to edit a table, you have to use Alter table

like image 43
Marc Avatar answered Mar 23 '26 07:03

Marc