Question

Pretty new to SQL Server. I tried to find a way to easily add a new column to a table. It's just taking an existing date column and giving it a different format. The only way I could get it to work was to create a new table, then drop the old table, and rename the new table.. Very inefficient surely

Use [Manipulate MC BS]
select*,
 CONVERT(date,[Time_stamp], 103) AS [Date Fixed]
into [Website Interactions - Raw2]
from [Website Interactions - Raw]
drop table [Website Interactions - Raw]
Use [Manipulate MC BS]
Go
sp_RENAME 'Website Interactions - Raw2','Website Interactions - Raw'
Go

How can I do this without creating a new table?

Thanks! Lucas

Was it helpful?

Solution

I think you should just add a computed column. These take up no additional storage space, but will allow you to see the result. The function is "build-in" to the table, kind of like having a view within the table. You can read about them here.

In your case, you would do:

ALTER TABLE
    ADD COLUMN [Date Fixed] AS CONVERT(date,[Time_stamp], 103);

This is very convenient. If you add new rows or change the data in [Time_stamp], the value of [Date Fixed] will automatically change.

OTHER TIPS

Did you try

ALTER TABLE [Website Interactions - Raw]
ADD [Date Fixed] TIMESTAMP

(use whatever data type you need, I used TIMESTAMP as an example)

And then you could do something like:

UPDATE [Website Interactions - Raw]
SET [Date Fixed]=CONVERT(date,[Time_stamp], 103)
WHERE 1;

The last WHERE 1 is not required if you're doing the update to all rows. If you only need to update some, set a condition: WHERE some_column=some_value;

Yes, this is still 2 queries, but should be much more efficient than copying a table into another one, then dropping the original and renaming new into old...

Hope this helps.

Not a good practice to save datetime or date datatype as strings(Varchar, Char) datatype but if you do want to do that you can do something like this.

ALTER TABLE TABLE_NAME
ADD NewColumn VARCHAR(10) DEFAULT CONVERT(date,GETDATE(), 103)

Update the column.

UPDATE TABLE_NAME
SET NewColumn = CONVERT(date,GETDATE(), 103)

My Suggestion

to store the data in DATE or DATETIME something like this

ALTER TABLE TABLE_NAME
ADD NewColumn DATE DEFAULT GETDATE()

And again you will need to update column for the existing records in your table.

Dropping Table and creating a new one may look an easier option. But if you have any Foreign keys or Permission on the table you may run into problems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top