views:

44

answers:

6

I have a column in a table of +15000 entries - I want to duplicate that entire column while retaining it's values and name it differently. I'm using Microsoft SQL Server Management Studio.

How do I go about that?

Thanks.

+4  A: 

Create a new column and then

UPDATE YourTable
SET NewColumn = OldColumn
Jakub Konecki
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
marc_s
+3  A: 
ALTER TABLE Boo
Add [NewColumnName] [datetype]
GO

Update Boo
Set NewColumnName = OldColumn
GO
Sage
A: 
INSERT into tbl (colname,fld1,fld2,fld3,fld4)  
 SELECT 'NEWNAME' as colname, fld1,fld2,fld3,fld4  
 FROM tbl where uniqid=[SOMEVAL]
FatherStorm
I think you may have misunderstood the question; this doesn't call for inserting new records.
LittleBobbyTables
If you post code or XML, **please** highlight those lines in the text editor and click on the "code" button (101 010) on the editor toolbar to nicely format and syntax highlight it!
marc_s
+1  A: 

Why not a computed column?

ALTER TABLE Foo ADD NewColumnName AS OldColumnName

This alos applies of you want to change a number into text for example

ALTER TABLE Foo ADD NewColumnName AS RIGHT('ABC000000' + CAST(OldColumnName AS varchar(10)), 10)

1       ABC0000001
2       ABC0000002
3       ABC0000003
4       ABC0000004
5       ABC0000005
gbn
A: 
BEGIN TRANSACTION

   ALTER TABLE myTable
       Add newcol NVARCHAR(8)
   GO 

   UPDATE myTable
       Set newcol = oldcol
   GO 

COMMIT TRANSACTION

Replace NVARCHAR(8) with whatever you current columns data type is.

Martin
+2  A: 

Based on your comments to the original question, I understand that you are trying to preserve 25 distinct values in ColumnA while converting the new ColumnB to hold 10 different values. I think you could do something like the code below. Modify my datatypes to match your situation.

declare @ColumnAConverter table (
    ColumnA nvarchar(max), 
    ColumnB nvarchar(max)
)

insert into @ColumnAConverter
    (ColumnA, ColumnB)
    select 'A', '1'
    union all
    select 'B', '1'
    union all
    select 'C', '2'
    /* ...continue for all 25 values in the original ColumnA */

update yt
    set ColumnB = c.ColumnB
    from YourTable yt
        inner join @ColumnAConverter c
            on yt.ColumnA = c.ColumnA
Joe Stefanelli
Thank you very much Joe - I will definitely give this a shot :)
Alex