tags:

views:

31

answers:

1

I have a table

TableName: MACAddresses
Columns:
- Computer
- MACAddress

I would like to create a sql script that creates a new column and correctly formats the mac address with the colon (ie with Substring) - To create a new column called CorrectMAC

How would I do this with Oracle?

+3  A: 

Here is some test data:

SQL> select * from MACAddresses
  2  /

  COMPUTER MACADDRESS
---------- ------------
       100 123456789abc
       200 acef35dd6ecc

SQL>

Adding the new column is quite straightforward:

SQL> alter table MACAddresses
  2      add corrected_MACAddress varchar2(17)
  3  /

Table altered.

SQL>

Note that you cannot make it NOT NULL at this point, because you already have some records in the table. So if you want to apply such a constraint, you need to populate it first.

This is the simplest way of updating the new column.

SQL> update MACAddresses
  2      set corrected_MACAddress = substr(macaddress, 1,2)||':'||
  3                                 substr(macaddress, 3,2)||':'||
  4                                 substr(macaddress, 5,2)||':'||
  5                                 substr(macaddress, 7,2)||':'||
  6                                 substr(macaddress, 9,2)||':'||
  7                                 substr(macaddress, 11,2)
  8  /

2 rows updated.

SQL> select * from MACAddresses
  2  /

  COMPUTER MACADDRESS   CORRECTED_MACADDR
---------- ------------ -----------------
       100 123456789abc 12:34:56:78:9a:bc
       200 acef35dd6ecc ac:ef:35:dd:6e:cc

SQL>

Now, if you had a more complicated pattern, or if you wanted to perform this operation on a regukar basis I suggest you expend the effort to turn it into a function, and perhaps remove that repetition at the same time.

Finally, if you wanted to enforce a mandatory constraint you can:

SQL> alter table MACAddresses
  2       modify corrected_MACAddress not null
  3  /

Table altered.

SQL>
APC
You could use that 'from dual connect by level' trick to do an arbitrary number of splits. Or an incomprehensible regexp on Oracle 10!
JulesLt
On 11g, this would be a good candidate for a virtual column, which would ensure that it is always consistent with the primary field.
Allan