Showing posts with label alreadyhas. Show all posts
Showing posts with label alreadyhas. Show all posts

Monday, March 12, 2012

how to add new column like existing one?

What's the best way to add a new column Y to an existing table that already
has existing column X, and I want Y to be x+3? I need to actually save the
value in the database, so yes, I do want a new column.On Sat, 29 Jan 2005 21:44:12 GMT, AFN wrote:

>What's the best way to add a new column Y to an existing table that already
>has existing column X, and I want Y to be x+3? I need to actually save th
e
>value in the database, so yes, I do want a new column.
>
Hi AFN,
ALTER TABLE MyTable
ADD Y AS x+3
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Add the column, run an update statement:
create table tablename
(
x int
)
insert into tablename values (1)
insert into tablename values (2)
insert into tablename values (3)
go
alter table tablename add y int null
go
update tablename
set y = x+3
go
alter table tablename alter column y in not null
go
Will you want all new values to be x + 3, or just initially? If the ONLY
values ever to be stored would be then you can use a computed column and
index it (this will persist the values so it doesn't have to be calculated
except the first time:
alter table tablename add y1 as (x+3)
create index tablnamePersistY1 on tablename(y1)
----
Louis Davidson - drsql@.hotmail.com
SQL Server MVP
Compass Technology Management - www.compass.net
Pro SQL Server 2000 Database Design -
http://www.apress.com/book/bookDisplay.html?bID=266
Note: Please reply to the newsgroups only unless you are interested in
consulting services. All other replies may be ignored :)
"AFN" < newsDELETETHECAPSgroupaccount@.DELETETHIS
yahoo.com> wrote in message
news:MsTKd.4579$e11.4113@.twister.socal.rr.com...
> What's the best way to add a new column Y to an existing table that
> already
> has existing column X, and I want Y to be x+3? I need to actually save
> the
> value in the database, so yes, I do want a new column.
>