I want to update column in a SQL 7 database. I'm interfacing with the
database using Enterprise Manager. The particular example could be
this. Table Name=bugs
name type
ant 1,2,4
beetle 2
cricket 1,2
I want to update bugs set bugs.type = '6'
where bugs.type = '2'
Obviously my question has to do with working around the commas. For
instance the outcome of the update I would like ant to have a type of
1,6,4, beetle a type of 6 and cricket a type of 1,6 |
Request for Question Clarification by
mathtalk-ga
on
17 Jun 2005 20:38 PDT
Hi, sm789-ga:
If you were to do this in SQL Server 2000, it would be simplified
slightly by the availability of a new string function
REPLACE(arg1,arg2,arg3):
[REPLACE -- MS Transact-SQL Reference]
http://msdn.microsoft.com/library/en-us/tsqlref/ts_ra-rz_76lh.asp
Under SQL Server 7.0 I'm afraid your will be stuck with some awkward
code that combines the use of patindex, substring, and string
concatenation to achieve mostly the same functionality. One
significant difference is that REPLACE will handle substitutions in
multiple locations within a string, although that is perhaps not
important to the application you sketch.
If only a single digit is involved (needs replacing), then the problem
is simplified (because only a character has to be replaced in the
update). But presumably the general problem will involve
comma-delimited strings containing integers of multiple digits.
In this case I could provide some sample code, making some assumptions
about the maximum length of the "type" field. Please advise me if
there are some further aspects of the "update" that need to be
addressed.
regards, mathtalk-ga
|
Clarification of Question by
sm789-ga
on
27 Jun 2005 11:03 PDT
I ended up doing something like this:
update bugs
set bugs.type = replace( type, '2', '6')
FROM bugs
It worked fine on SQL 7.
|
Request for Question Clarification by
mathtalk-ga
on
27 Jun 2005 15:15 PDT
Cool! Keep in mind that as soon as the strings start mananging
multi-digit numbers, there's a risk of changing "12" to "16" when all
you really wanted was to change "2" to "6". For greater safety, I'd
add a comma at the beginning and end of the target string
(temporarily, just as part of an expression) and do the replace on:
',2,' goes to ',6,'
Then "substring" away the beginning and ending commas to get the final expression.
best wishes, mathtalk-ga
|