views:

67

answers:

4

What would the command be for Microsoft SQL Server 2008 to alter an existing column to allow for more characters? Would this have an effect on any previous entries in the column if I'm only expanding it?

I have a URL column that I need to add about 100 characters to.

+5  A: 
ALTER TABLE [table] ALTER COLUMN [column] NVARCHAR(newsize)

And increasing the size won't affect your data.

Joe
You should specify NULL or NOT NULL as well, just to be sure that nullability is not changed at the same time.
Philip Kelley
+2  A: 
ALTER TABLE myTable ALTER COLUMN myColumn varchar(100)
GO

This would not involve the risk of losing data, because you are expanding the size of the column.

Randy Minder
+1  A: 
ALTER TABLE tab ALTER COLUMN c VARCHAR(200)
Roland Bouman
A: 

You can use SQL Server Management Studio to generate the code to do this yourself. Just modify the table in the designer so that the column is wider and click "Generate change script" (under the "Table designer" menu).

Depending on the change you make the code to modify a table can be fairly complex.

Kragen
This isn't always the best way. If for some reason the update fails it will generally wack all of your foreign keys. Also, if you have FILESTREAM fields, it will drop the filestream association. Generally speaking the designer is the last place you want to try and use to modify your tables.
Chris Lively
BTW, the reason why is that the designer first drops all of the foreign key references, then drops the old table, then creates a new one in its place, then puts the data back in, and finally adds the foreign key references. If it fails it doesn't roll back the entire transaction. As far as filestream, the designer just doesn't know anything about it. So when it goes to recreate the table, it leaves that part out.
Chris Lively
I found the designer to be a good way to learn how to write DDL scripts. Later, I found the designer to be a good way to learn how *not* to write DDL scripts.
Philip Kelley