Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-sql replace on text field

I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.

I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.

Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.

like image 923
PeteT Avatar asked Nov 14 '08 10:11

PeteT


People also ask

How do I replace text in a column in SQL?

SQL Server REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: The search is case-insensitive.

How do I replace a string in a column in SQL Server?

If you'd like to replace a substring with another string, simply use the REPLACE function. This function takes three arguments: The string to change (which in our case was a column). The substring to replace.

How do I update a text field in SQL?

Use UPDATETEXT to change only a part of a text, ntext, or image column in place. Use WRITETEXT to update and replace a whole text, ntext, or image field. This feature will be removed in a future version of Microsoft SQL Server.


2 Answers

Here is the sample query to update table with text column using REPLACE function. Hope this is useful for you.

UPDATE <Table> set textcolumn= REPLACE(SUBSTRING(textcolumn,1,DATALENGTH(textcolumn)),'findtext','replacetext')  WHERE <Condition> 
like image 178
suryakiran Avatar answered Sep 25 '22 08:09

suryakiran


I am afraid you cannot do it within a function

When you try to declare a function like:

create function dbo.textReplace( @inText as text) returns text as  begin     return 'a' -- just dummy code end 

You will get the following error:

The text data type is invalid for return values. 

In other words you could not write a simple equivalent of REPLACE function for the text data type

like image 33
kristof Avatar answered Sep 25 '22 08:09

kristof