sql server 2008 - Update column by parsing another column with T-SQL -
i have table , data in database:
tblphotos
id | title | description ------------------------------ 1 | null | data - title 123 - subtitle - photographer: john doe 2 | null | data - photographer: jane doe 3 | null | data - title 345 - photographer: john doe jr
the data in description
column comes in 2 formats:
{garbage data} - {title data} - photographer: ..., or {garbage data} - photographer: ...
basically, have thousands of rows, title
column empty. need somehow pull out of description
column.
the title
exists between first dash , and last dash of description
column. here's data should like:
tblphotos
id | title | description ------------------------------------------------------------------------------------- 1 | title 123 - subtitle | data - title 123 - subtitle - photographer: john doe 2 | null | data - photographer: jane doe 3 | title 345 | data - title 345 - photographer: john doe jr
how can make script parse column, , update column parsed data?
the location of first dash easy: charindex('-', description)
. location of second dash easy, too, want location of last dash. that's bit harder because have reverse string it: len(description) - charindex('-', reverse(description))
. stuff in between need find length subtracting 2 positions:
substring(description, charindex('-', description) + 1, len(description) - charindex('-', reverse(description))) - charindex('-', description)
putting get:
update tblphotos set title = rtrim(ltrim( substring(description, charindex('-', description) + 1, len(description) - charindex('-', reverse(description)) - charindex('-', description)))) title null
Comments
Post a Comment