Saturday, February 5, 2011

SQL query to extract text from a column and store it to a different column in the same record.

I need some help with a SQL query...

I have a SQL table that holds in a column details of a form that has been submitted. I need to get a part of the text that is stored in that column and put it into a different column on the same row. The bit of text that I need to copy is always in the same position in the column.

Any help would be appreciated guys... my mind has gone blank :">

  • UPDATE  mytable
    SET     other_column = SUBSTRING(column, begin_position, length)
    
    From Quassnoi
  • UPDATE table SET Column2 = SUBSTRING(Column1, startPos, length)

    Irfan Mulic : There is no "where" statement - meaning this will update the all records in this table.
  • You may just want to use a computed column. This way if the source string changes, your computed column is still correct. If you need to seek to this substring then you might want a persisted computed column if your db supports it.

    John Sansom : +1: For thinking outside the box :-) You could also make it a persisted computer column.
    Rob Garrison : Perfect answer. If you persist the column, you can also index it.
    From
  • What if the value you wanted to copy was in a different position in each record, but always followed the same text?

    Richard West : I would use CHARINDEX ( string_expression , target_expression) to get the starting position of text string, then use SUBSTRING to pull it out of the field.

0 comments:

Post a Comment