At first if you need to split such values and if you need to do it often then it would be easier to change your db schema:
- rename column
name
into last_name
- add column
first_name
It has some advantages. You probably want to search employees by last name, and it is easy when you simply have such column. If last name is a part of name
column then you must search using LIKE
which is slower and worse.
Now you will have to change some data. If you have comma in last_name
then in such column there is first and last name and you must split it.
If you have charindex()
function you can do it with:
UPDATE employees SET last_name=substring(last_name FROM charindex(',', last_name)+1), first_name=substring(last_name FROM 1 FOR charindex(',', last_name)-1) WHERE charindex(',', last_name) > 0;
(you can also use TRIM()
to remove spaces before/after comma which will be copied)
From comments I see that your version of Informix do not have CHARINDEX()
function so you must upgrade db engine or use technique other than clean SQL.
If you can use programming language like Java or Python (for this example I use Jython: it is Python that work in Java environment and can use JDBC driver) you can:
db = DriverManager.getConnection(db_url, usr, passwd)
# prepare UPDATE:
pu = db.prepareStatement("UPDATE employee SET last_name=?, first_name=? WHERE id=?")
# search for names that must be changed:
pstm = prepareStatement("SELECT id, last_name FROM employee WHERE last_name LIKE '%,%')
# for each record found remember its `id`, split `first_name` and update it:
rs = pstm.executeQuery()
while (rs.next()):
id = rs.getInt(1)
name = rs.getString(2)
first_name, last_name = name.split(',')
pu.setString(1, last_name.strip())
pu.setString(2, first_name.strip())
pu.setInt(3, id)
rc = pu.executeUpdate()
select dbinfo('version','full') from sysmaster:sysdual
? thecharindex
function is available only at version 11.70. (at version 11.70 you can use thesubstring_index
for this too). If you are working with an older version, so, will need create a procedure to execute your cut – Romeliaromellesubstr()
for older versions of informix Ex: substr('abcde', 1, 2). It looks like our older version of informix uses a 1 based index (ie. starts with 1 instead of 0) – Gheber