SQL Server find and replace in TEXT field - sql-server-2005

I have a database in SQL Server 2005 that was brought up from SQL Server 2000 and is still using TEXT type fields instead of varchar(max).
I need to find and replace a string of characters in the text field but all of the examples of how to do this that I have found don't seem like they would work for me. It seems the UPDATETEXT command requires that the two parameters "insert_offset" and "delete_length" be set explicitly but the string i am searching for could show up in the text at any point or even at several points in the same cell. My understanding of these two parameters is that the string im searching for will always be in the same place, so that insert_offset is the number of spaces into the text that the UPDATETEXT command will start replacing text.
Example: Need to find: <u> and Replace it with: <u>
Text field example:
*Everyone in the room was <b><u>tired</u>.</b><br>Then they woke <b><u>up</u>.
Can anyone help me out with this? THANKS!

I finally figured it out. It was buried in the comments to the article jfrobishow published. Thank you SO much.
Here is the whole response that led me to the solution:
quote:Originally posted by fredclown
If you use SQL 2005 you can use replace with a text type. All you have
to do is the below ...
field = replace(cast(field as varchar(max)),'string' ,'replacement')
Easy as pie.
Two thumbs up to Fredclown!!! command
work like a charm for me as well. This
is what I wrote my Update statement to
Find and Replace in a Text field in
SQL server 2005 database
UPDATE TableName SET DBTextField = REPLACE(CAST(DBTextField AS varchar(MAX))
,'SearchText', 'ReplaceText')
FROM TableName
WHERE CHARINDEX('SearchText',CAST(DBTextField as varchar(MAX)))>0
Note:that this may truncate the size of you dbfield , but if is a long text column make it nvarchar(max) and you should not get none truncation!

Related

Replace value in multiple strings without charindex

so This is a sample of my DB Values
UPDATE page p SET p.content = REPLACE(p.content, SUBSTRING(p.content, CHARINDEX('php?id=', p.content) +1), CONCAT('php?id=',p.course)) WHERE p.content LIKE '%php?id=%' AND p.content NOT LIKE CONCAT('%','php?id=',p.course,'%');
I'm Trying to only get the text after php?id= which is a number and change it to the correct number which is the course column
so for example the first value should be changed to
4|Enjoy your training!<a href="*/view.php?id=4">
Unfortunately charindex keeps giving me an Error
Any Help on how to Make this thing work without charindex as i Believe our server does not support this function
UPDATE: Charindex didnt exist in mysql so i had to use LOCATE fuction instead. Also i wasnt using the root password for the whole server, just the root password for the db
Thanks for the heads up!
Now just need the query to correctly update... as it removes just everything after <a href etc etc and doesnt replace

#Dblookup and formatting on web

I have been developing a web application using domino, therein I have dblookup-ing the field from notes client; Now, this is working fine but the format of value is missing while using on web.
For example in lotus notes client the field value format is as above
I am one, I am two, I am one , I am two, labbblallalalalalalalalalalalalalalalalalalaallllal
Labbbaalalalallalalalalalaalallaal
Hello there, labblalalallalalalllaalalalalalalalalalalalalalalalalalalalalalalala
Now when I retrieve the value of the field on web it seems it takes 2 immediate after 1. and so forth, I was expecting line feed here which is not happening.
The field above is multi valued field. Also on web I have used computed text which does db lookup from notes client.
Please help me what else could/alternate solution for this case.
Thanks
HD
Your multi-valued field has display options associated with it and the Notes client honors those. Obviously, your options are set up to display entries separated by newlines.
The computed text that you are using for the web does not have options like that and the field options are irrelevant because you aren't displaying the field. Your code has to insert the #Newlines. That's pretty easy because #DbLookup returns a list, and if you concatenate a list and a scalar, the scalar will be appended to each element of the list. (Look at the third example under "concatenation, pairwise" here to see what I mean.
The way you've worded your question is a little unclear to me, but what you need in your computed text formula is either something like this:
list := #DbLookup(etc,. etc.);
list + #Newline;
Or something like this:
multiValueFieldContainingListWithDbLookupResult + #NewLine;
I used #implode(Dblookupreturnedvalue;"");
thanks All :)

Best way to add target ='_blank' for href in a string using UDF

I've got data in sql server 2012 that contains text with links test with out target i need to add target for the string data. I need to create a User defined function for that. Does any one have any sample code for this.
Example text -
If you've ever thought one of your text message threads was so good it deserved to be published, you may be on to something.view. njkhj In future iterations, users will be able to post .<br><br>You may update your email address at any time by going to sdffsd. Our whole goal is to have the reader go through an entire narrative arc in five minutes and consume it in a way that's native to mobile," says Gupta go to sdfsdf which is one of my favorite books, is told as letters back and forth between the two main
I think a simple replace would do the trick
Declare #String varchar(max) = 'Some large text with a link to content'
Select Replace(#String,' href=','_target="blank" href=')
Returns
(No column name)
Some large text with a <a _target="blank" href="test/test">link</a> to content
We can also use
SELECT REPLACE(text,'<a','<a target="_blank" ');
Go

MySQL: How can I remove trailing HTML from a field in the database?

I want to remove some rogue HTML from a DB field that is supposed to contain a simple filename. Example of ok field:
myfile.pdf
Example of not ok field:
myfile2.pdf<input type="hidden" id="gwProxy" />...
Does anyone know a query I can run that can remove the HTML part but leave the filename? i.e. remove everything from the first < character onwards.
Lets assume the field is called myattachment and is defined as a varchar(250) and the table is called mytable in a MySQL database.
Background info (not necessary to read):
The field in our database is supposed to contain filenames however, due to a issue (documented here) some of the fields now contain a filename and some rogue HTML. We have fixed the root issue and now need to fix the corrupt fields. In the past I have replaced text using this kind of query:
UPDATE mytable SET myattachment = replace(myattachment, 'JPG', 'jpg') WHERE myattachment LIKE '%JPG';
This query seems to work ok, can anyone see any issues with it?
UPDATE mytable
SET myattachment = SUBSTRING_INDEX(myattachment, '<', 1)
WHERE `myattachment` LIKE '%<%';
For docs on SUBSTRING_INDEX see the mysql manual page.

Data in a table with carriage return?

In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return.
Eg:
insert into table values ('test1
test2
test3
test4');
When I retrieve it, I get the message in a line
test1 test2 test3 test4
The carriage return is treated as a single character.
Is there way to get the carriage returns or its just the way its going to be stored?
Thanks for the help guys!!!
Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert.
I return the data to the app development (C++) and may be some data or report viewer.
I don't want to manipulate on the data.
You can store Carriage return in the database. The problem here is that you are using SQL Server Management Studio to display the results of your query. You probably have it configured to show the results in a grid. Change the configuration of SSMS to show results to text and you will see the carriage returns.
Right click in the query window -> Results To -> Results To Text
Run your query again.
INSERT INTO table values('test1' + CHAR(10) + 'test2' + CHAR(10) + 'test3' + CHAR(10) + 'test4')
This should do it. To see the effect, switch the query result window to plain text output.
Regards
IIRC, using chr(13) + chr(10) should works.
insert into table values ('test1' + chr(13) + chr(10) + 'test2' );
Can you please clarify how you retrieve the data back from the database? What tool do you use? The data probably contains the carriage returns but it's not displayed if you get the results in grid (try the results in text option)
You might need to put in a "\n" instead of a literal carriage return.
The carriage return is stored as is. The problem here is that your sql client is not understanding it. If you did a raw dump of this data you'll see that the carriage returns are there in the data.
I use DBArtisan at work and it seems to work fine. However isql seems to have the same problem that you reported.
Is this result in your HTML or in Query analyser? If it's in HTML, have a look at the source code and it might appear correct there, in which case you'd have to replace the crlf characters with <br /> tags.
I'm also thinking that there used to be attributes you could add to an HTML textarea to force it to send carriage returns in certain ways -- soft or hard? I haven't looked that up, perhaps someone could do that.
But SQL Server does save the two characters in my experience. In fact I did exactly as you described here a few days ago using SQL 2005 and each line break has two unprintable characters.
I am using SQLite to store multiline texbox and got something like that when retrieving data stored and showing it on any object (txtboxes, labels, etc.). Anytime I copied data into NotePad/WordPad or similar, I could see that carriage returns were stored, they simply weren't show in the ASP page.
Found the answer here:
http://www.mikesdotnetting.com/Article/20/How-to-retain-carriage-returns-or-line-breaks-in-an-ASP.NET-web-page
hope that helps.
My code example:
C#:
protected void Page_Load(object sender, EventArgs e)
{
String str = Request.QueryString["idNoticia"];
this.dsNewsDetails.FilterExpression = "idNoticia=" + str;
}
ASPX:
<asp:Label ID="BodyLabel"
runat="server" style="font-size: medium"
Text='<%# Eval("body").ToString().Replace(Environment.NewLine,"<br/>") %>' Width="100%" />
Note: as mentioned in the link provided, Environment.NewLine works both for C# and VB
If you switch the output to plain text you can see the data in different lines.
To switch output go to Tools>Options>Query Resultsand set default destination to: text.
You can also try hitting Ctrl+p before executing query. Hope it helps.