nix, shell, perl, php, mysql and mac os x tips and tricks

Monday, April 24, 2006

ms sql for search-and-replace based on key/value table (not really tested)

01.   DECLARE @word1 varchar(1000)
02.    DECLARE @word2 varchar(1000)
03.    DECLARE word_cursor CURSOR LOCAL fast_forward FOR
04.    SELECT old_word, new_word FROM word_replace_table
05. 
06.    OPEN word_cursor
07. 
08.    FETCH NEXT FROM word_cursor INTO @word1, @word2
09. 
10.WHILE @@FETCH_STATUS = 0
11. 
12.BEGIN
13. 
14. 
15.  SET xact_abort ON
16.  BEGIN tran
17. 
18.  DECLARE @otxt varchar(1000)
19. 
20.  SET @otxt = @word1 /****/
21.  DECLARE @ntxt varchar(1000)
22. 
23.  SET @ntxt = @word2 /****/
24. 
25.  DECLARE @txtlen int
26.  SET @txtlen = len(@otxt)
27. 
28.  DECLARE @ptr BINARY(16)
29.  DECLARE @pos int
30.  DECLARE @id int
31.  DECLARE curs CURSOR LOCAL fast_forward
32.  FOR
33.  SELECT
34. 
35.  productId,
36.  textptr(description),
37.  charindex(@otxt, description)-1
38.  FROM
39.  product
40.  WHERE
41.  description
42.  LIKE
43.  '%' + @otxt +'%'
44. 
45.  OPEN curs
46. 
47.  FETCH NEXT FROM curs INTO @id, @ptr, @pos
48. 
49.  WHILE @@fetch_status = 0
50. 
51.  BEGIN
52. 
53.  print 'Text found in row id=' + cast(@id AS varchar) + ' at pos=' + cast(@pos AS varchar)
54. 
55.  updatetext product.description @ptr @pos @txtlen @ntxt
56. 
57.  FETCH NEXT FROM curs INTO @id, @ptr, @pos
58. 
59.  END
60. 
61.  CLOSE curs
62. 
63.  DEALLOCATE curs
64. 
65.  commit tran
66. 
67.    FETCH NEXT FROM word_cursor INTO @word1, @word2
68.END
69. 
70.    CLOSE word_cursor
71.    DEALLOCATE word_cursor

No comments:

Post a Comment