SQL string replace based on WHERE clause - sql

I have a memo field which may contain & and the HTML equivalent &. I need to write a script to ensure that all instances of ampersand are the HTML equivalent. Have the below script but the WHERE clause does not seem to factor the individual instances (strings) of & in the memo field, just the field as a whole... Any ideas on how to accomplish this? Thanks.
UPDATE
STOCKMEM
SET
INETFDESC = CAST(REPLACE(CAST(INETFDESC as NVarchar(MAX)),'&','&') AS NText)
WHERE
INETFDESC LIKE '%&%'
AND INETFDESC NOT LIKE '%&%'

Try this instead:
UPDATE STOCKMEM
SET INETFDESC = CAST(
REPLACE(
REPLACE(
CAST(INETFDESC as NVarchar(MAX))
,'&','&')
, '&', ,'&')AS NText)
WHERE INETFDESC LIKE '%&[^amp;]%'
The first replace will change & to &, and the second will replace all & back to &.
BTW, Please note that NText data type is depricated and you should convert it to nvarchar(max).
From MSDN:
IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.

You can accomplish the same thing by this:
UPDATE STOCKMEM
SET INETFDESC = CONVERT(NVARCHAR(MAX),(REPLACE(REPLACE(INETFDESC, '&', '&'), '&', '&')))
WHERE INETFDESC LIKE '%&%'

Related

SQL Query to parse XML and remove data and send remaining results to multiple columns

Is there a way to parse XML string data from a column from a table and easily be able to remove parts of the XML string with a wildcard automatically?
Example:
Example:
<audit><fieldid>id="John"<fieldid>id="bob</audit>
How would i be able to remove just <fieldid>id="bob?
How would i be able to remove just <fieldid>id="bob?
If there are more values after <fieldid>id="bob, how would i be able remove those as well, but keep the </audit> in place at the end.
I have tried the following Update Statement and it did not work with a wildcard:
Update Table
Set column=Replace(Column, '<fieldid>id="bob%', </Audit>
I have tried the following but wildcards in a replace function do not work:
update table
set column=replace(column,'id="bob%',
Assumption:
the pattern id="bob will only occur once.
This should do it. You just need to replace the variable #var with your column:
DECLARE #Var VARCHAR(MAX) = '<audit><fieldid>id="John"<fieldid>id="bob</audit>';
SELECT REPLACE(#Var, SUBSTRING(#Var, PATINDEX('%<fieldid>id="bob%', #Var), PATINDEX('%<%', SUBSTRING(#Var, PATINDEX('%<fieldid>id="bob%', #Var)+1, LEN(#Var)))), '');
RESULT:
To Answer your comment "Is it possible to have the script remove all values after bob and be replaced with ?"
DECLARE #Var VARCHAR(MAX) = '<audit><fieldid>id="John"<fieldid>id="bob<fieldid>id="John"</audit>';
SELECT REPLACE(#Var, SUBSTRING(#Var, PATINDEX('%<fieldid>id="bob%', #Var), PATINDEX('%</audit>%', SUBSTRING(#Var, PATINDEX('%<fieldid>id="bob%', #Var)+1, LEN(#Var)))), '');
RESULT:

SQL wont let me replace a quote in SELECT statement

I am trying to remove double quotes " from a column in my SQL export and I get an error, after researching the proper way... this is one of the ways I have tried....
SELECT
'293453' as custnum,
REPLACE(Orders.Order_Comments, '"', '') as FULFILL1,
OrderDetails.OrderID as OrderID2, etc.
The resulting error is:
Your SQL is invalid: Argument data type text is invalid for argument 1 of replace function.
Your Orders.Order_Comments columns is of type text. You can't use the REPLACE() function with that data type. It only works with char/varchar/nchar/nvarchar.
To fix this, the best thing to do is ALTER the table to use a varchar(max) column. The text type is depcrecated, anyway. But, if that's not an option, you'll have to cast it in the query:
REPLACE(CAST(Orders.Order_Comments as varchar(max)), '"', '')
Note that this is potentially very slow.
Take a look at this answer: SQL Server find and replace in TEXT field
The text data type is not valid for use with replace, so you need to cast it as VARCHAR(MAX)
REPLACE(CAST(Orders.Order_Comments AS VARCHAR(MAX)), '"', '')
Try this:
select REPLACE(isnull(Orders.Order_Comments,''), '"', '') as order_comments
from orders

SQL Server - Adding a string to a text column (concat equivalent)

How do you add a string to a column in SQL Server?
UPDATE [myTable] SET [myText]=' '+[myText]
That doesn't work:
The data types varchar and text are incompatible in the add operator.
You would use concat on MySQL, but how do you do it on SQL Server?
like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:
-- create a test table
create table test (
a text
)
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works:
update test set a = cast ( a as nvarchar(max)) + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added
Stop using the TEXT data type in SQL Server!
It's been deprecated since the 2005 version. Use VARCHAR(MAX) instead, if you need more than 8000 characters.
The TEXT data type doesn't support the normal string functions, while VARCHAR(MAX) does - your statement would work just fine, if you'd be using just VARCHAR types.
The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.
In fact, image, ntext, and text are all deprecated.
ntext, text, and image data types will
be removed in a future version of
MicrosoftSQL Server. Avoid using these
data types in new development work,
and plan to modify applications that
currently use them. Use nvarchar(max),
varchar(max), and varbinary(max)
instead.
That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).
UPDATE test SET a = CONCAT(a, "more text")
hmm, try doing CAST(' ' AS TEXT) + [myText]
Although, i am not completely sure how this will pan out.
I also suggest against using the Text datatype, use varchar instead.
If that doesn't work, try ' ' + CAST ([myText] AS VARCHAR(255))
To Join two string in SQL Query use function CONCAT(Express1,Express2,...)
Like....
SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

String update in SQL Server

Currently I have varchar field. The delimiter is "$P$P$".
The delimiter will appear at least once and at most twice in the varchar data.
Eg.
Sample Heading$P$P$Sample description$P$P$Sample conclusion
Sample Heading$P$P$Sample Description
If the delimiter appears twice, I need to insert a text before the second occurance of the delimiter.
Eg:
Sample Heading$P$P$Sample DescriptionINSERT TEXT HERE$P$P$Sample Conclusion
If the delimiter occurs only once, then I need to insert a text at the end of the field.
Eg:
Sample Heading$P$P$Sample DescriptionAPPEND TEXT HERE
How this can be done in SQL query?
If you are going to do a lot of string manipulation you might want to use a CLR (.net) function. Since SQL Server isn't exactly made for string manipulation.
Or even better, pull this data back to your application and do it in code.
I even think you can't do it using the default SQL Server String functions
The CharIndex function has an optional 3rd parameter that allows you to specify the starting position of the search. You can use this to find the 2nd occurrence of a string using CharIndex. You can also use the stuff function to insert a string in to another string.
Example:
Declare #Temp Table(Data VarChar(8000))
Insert Into #Temp Values('Sample Heading$P$P$Sample description$P$P$Sample conclusion')
Insert Into #Temp Values('Sample Heading$P$P$Sample Description')
Select len(Data),
CharIndex('$P$P$', Data + '$P$P$',CharIndex('$P$P$',Data) + 1),
Stuff(Data + ' ', CharIndex('$P$P$', Data + '$P$P$',CharIndex('$P$P$',Data) + 1), 0, 'Text Here')
From #Temp
I realize it looks like a mess, but I do encourage you to understand how this works because you may need something similar in the future.
instead of using delimiters, why not creating 3 columns or if you only want one --> an xml field?

Can I do a find/replace in t-sql?

I basically have an xml column, and I need to find and replace one tag value in each record.
For anything real, I'd go with xpaths, but sometimes you just need a quick and dirty solution:
You can use CAST to turn that xml column into a regular varchar, and then do your normal replace.
UPDATE xmlTable SET xmlCol = REPLACE( CAST( xmlCol as varchar(max) ), '[search]', '[replace]')
That same technique also makes searching XML a snap when you need to just run a quick query to find something, and don't want to deal with xpaths.
SELECT * FROM xmlTable WHERE CAST( xmlCol as varchar(max) ) LIKE '%found it!%'
Edit: Just want to update this a bit, if you get a message along the lines of Conversion of one or more characters from XML to target collation impossible, then you only need to use nvarchar which supports unicode.
CAST( xmlCol as nvarchar(max) )
To find a content in an XML column, look into the exist() method, as described in MSDN here.
SELECT * FROM Table
WHERE XMLColumn.exist('/Root/MyElement') = 1
...to replace, use the modify() method, as described here.
SET XMLColumn.modify('
replace value of (/Root/MyElement/text())[1]
with "new value"
')
..all assuming SqlServer 2005 or 2008. This is based on XPath, which you'll need to know.
update my_table
set xml_column = replace(xml_column, "old value", "new value")