//  home   //  advanced search   //  news   //  categories   //  sql build chart   //  downloads   //  statistics
 ASP FAQ 
Home
ASP FAQ Tutorials

   8000XXXX Errors
   ASP.NET 2.0
   Classic ASP 1.0
   Databases
      Access DB & ADO
      General SQL Server & Access Articles
      MySQL
      Other Articles
      Schema Tutorials
      Sql Server 2000
      Sql Server 2005
   General Concepts
   Search Engine Optimization (SEO)

Contact Us
Site Map

Search

Web
aspfaq.com
tutorials.aspfaq.com
sqlserver2000.databases.aspfaq.com

ASP FAQ Tutorials :: Databases :: Sql Server 2000 :: How do I handle REPLACE() within an NTEXT column in SQL Server?


How do I handle REPLACE() within an NTEXT column in SQL Server?

I recently was confronted with a problem where a piece of text that was included in many NTEXT column values in a table needed to be replaced with another piece of text. You can't issue normal REPLACE statements against NTEXT columns, so this seemed to be a bit of a challenge — issuing a REPLACE() against a TEXT or NTEXT column in SQL Server yields: 
 
Server: Msg 8116, Level 16, State 1, Line 1 
Argument data type text is invalid for argument 1 of replace function.
 
And from within an ASP page: 
 
Microsoft OLE DB Provider for SQL Server error '80040e14'  
Argument data type text is invalid for argument 1 of replace function.
 
Initially, I thought I would have to resort to writing an app or web page, pull the NTEXT data out of the database, do the replace in VBScript or C#, and update the whole value. I wasn't really looking forward to writing such an app, much less debug it until I knew it would perform acceptably. 
 
UPDATETEXT and a quick and dirty cursor really saved my bacon on this one. As long as you have a unique identifier in the table (e.g. an INDENTITY value or a GUID), you can loop through the table and, row by row, issue UPDATETEXT for each instance of the 'bad' text you want to replace. 
 
This was tested successfully, as is, in SQL Server 2000 and SQL Server 2005. Though, in SQL Server 2005, there's no reason you should be delaying the conversion of your column(s) from TEXT/NTEXT to VARCHAR(MAX)/NVARCHAR(MAX) - these new types are far more flexible and really are, as Erland describes it, "first class citizens" in the SQL Server type world. 
 
If you are using SQL Server 7.0, see the notes below. 
 
Run this script in Query Analyzer to get a feel for it... I will be replacing all instances of 'food' with the word 'fudge'. Do *NOT* try to run this script where @oldString is a subset of (or equal to) @newString, e.g. 'food' replaced by 'food' or 'food poison' ... you will get an infinite loop. I have commented the 5 or 6 lines that need to change if the column is TEXT rather than NTEXT. 
 
USE TempDB; 
GO 
 
SET NOCOUNT ON; 
 
CREATE TABLE dbo.data 

    DataID INT PRIMARY KEY, 
    txt NTEXT -- change to TEXT 
); 
GO 
 
INSERT dbo.data 
    SELECT 1, N'bar foodfood food har sammy' 
    UNION ALL SELECT 2, N'bar sammy food' 
    UNION ALL SELECT 3, N'bar fooblat sammy' 
    UNION ALL SELECT 4, N'food'; 
 
DECLARE 
    @TextPointer BINARY(16), 
    @TextIndex INT, 
    @oldString NVARCHAR(32), -- change to VARCHAR 
    @newString NVARCHAR(32), -- change to VARCHAR 
    @lenOldString INT, 
    @currentDataID INT; 
 
SET @oldString = N'food'; -- remove N 
SET @newString = N'fudge'; -- remove N 
 
IF CHARINDEX(@oldString, @newString) > 0  
BEGIN 
    PRINT 'Quitting to avoid infinite loop.'; 
END 
ELSE 
BEGIN 
    SELECT 'Before replacement:'; 
 
    SELECT DataID, txt FROM data; 
 
    SET @lenOldString = DATALENGTH(@oldString)/2; -- remove /2 
 
    DECLARE irows CURSOR 
        LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
        SELECT 
            DataID 
        FROM 
            dbo.data 
        WHERE 
            PATINDEX('%'+@oldString+'%', txt) > 0; 
 
    OPEN irows; 
 
    FETCH NEXT FROM irows INTO @currentDataID; 
 
    WHILE (@@FETCH_STATUS = 0) 
    BEGIN 
 
        SELECT 
            @TextPointer = TEXTPTR(txt),  
            @TextIndex = PATINDEX('%'+@oldString+'%', txt) 
        FROM 
            dbo.data 
        WHERE 
            DataID = @currentDataID; 
 
        WHILE 
        ( 
            SELECT 
                PATINDEX('%'+@oldString+'%', txt) 
            FROM 
                dbo.data 
            WHERE 
                DataID = @currentDataID 
        ) > 0 
        BEGIN 
            SELECT 
                @TextIndex = PATINDEX('%'+@oldString+'%', txt)-1 
            FROM 
                dbo.data 
            WHERE 
                DataID = @currentDataID; 
 
            UPDATETEXT dbo.data.txt @TextPointer @TextIndex @lenOldString @newString; 
        END 
 
        FETCH NEXT FROM irows INTO @currentDataID; 
    END 
 
    CLOSE irows; 
 
    DEALLOCATE irows; 
 
    SELECT 'After replacement:'; 
 
    SELECT DataID, txt FROM data; 
END 
 
DROP TABLE dbo.data;
 
(Note that UPDATETEXT does not cause triggers to fire like a normal UPDATE statement would... so you don't have to disable a trigger, for example, responsible for auditing row changes, however take note that the changes will not be recorded if you are using this methodology.) 
 
SQL Server 7.0 
 
With SQL Server 7.0, it appears you have to set the BULKCOPY attribute to true, otherwise you will get the following error: 
 
Server: Msg 7130, Level 16, State 1, Line 47 
UpdateText WITH NO LOG is not valid at this time. Use sp_dboption to set the 'select into/bulkcopy' option on for database 'pubs'.
 
You can set the BULKCOPY attribute with the following setting: 
 
EXEC master.dbo.sp_dboption 'pubs', 'BULKCOPY', 'true'
 
(Change to false after you've run the script... you should only be performing this kind of task manually and occasionally, and this is not a setting you want retained permanently.)

Related Articles

Are there tools available for auditing changes to SQL Server data?
Can I create an index on a BIT column?
Can I have optional parameters to my stored procedures?
Can I implement an input mask in SQL Server?
Can I make SQL Server format dates and times for me?
Can I start IDENTITY values at a new seed?
Can SQL Server tell me which row was inserted most recently?
How can I learn more about undocumented SQL Server stored procedures?
How can I make my SQL queries case sensitive?
How do I audit changes to SQL Server data?
How do I connect to a non-default instance of SQL Server?
How do I connect to SQL Server on a port other than 1433?
How do I create a cross-tab (or "pivot") query?
How do I determine if a table exists in a SQL Server database?
How do I drop a SQL Server database?
How do I find all the available SQL Servers on my network?
How do I get a list of SQL Server tables and their row counts?
How do I get rid of Named Pipes / DBNMPNTW errors?
How do I get the correct date/time from the msdb.sysjob* tables?
How do I get the nth row in a SQL Server table?
How do I get the result of dynamic SQL into a variable?
How do I hide system tables in SQL Server's Enterprise Manager?
How do I know which version of SQL Server I'm running?
How do I limit the number of rows returned in my resultset?
How do I load text or csv file data into SQL Server?
How do I manage changes in SQL Server objects?
How do I monitor SQL Server performance?
How do I prevent linked server errors?
How do I reclaim space in SQL Server?
How do I recover data from SQL Server's log files?
How do I search for special characters (e.g. %) in SQL Server?
How do I start SQL Server Agent from ASP?
How do I time my T-SQL code?
How do I upsize from Access to SQL Server?
How do I upsize my MSDE database to full-blown SQL Server 2000?
How do I use a variable in a TOP clause in SQL Server?
How do I use GETDATE() within a User-Defined Function (UDF)?
How should I store an IP address in SQL Server?
Schema: How do I find all the foreign keys in a database?
SQL Server & MSDE
What are reserved Access, ODBC and SQL Server keywords?
What are the capacities of Access, SQL Server, and MSDE?
What are the main differences between Access and SQL Server?
What do I need to know about SQL Server 2000 SP4?
Where else can I learn about SQL Server?
Where is SP4 for SQL Server 2000?
Why am I having problems with SQL Server 2000 SP3 / SP3a?
Why can't I install SQL Server on Windows Server 2003?
Why can't I install SQL Server on Windows XP?
Why can't I use LIKE '%datepart%' queries?
Why do I get "Login failed for user '\'."?
Why do I get 'object could not be found' or 'invalid object name'?
Why do I get errors about master..spt_values?
Why do I get script errors in Enterprise Manager's 'taskpad' view?
Why do I get SQLSetConnectAttr Failed errors?
Why do I have problems with views after altering the base table?
Why does EM crash when I get an error in a stored procedure?
Why does Enterprise Manager return 'Invalid cursor state'?
Why does my DELETE query not work?
Why does sp_spaceused return inaccurate values?
Why is Enterprise Manager slow at expanding my database list?
Why is my app slow after upgrading from SQL Server 7 to 2000?
Why is tempdb full, and how can I prevent this from happening?
Why should I consider using an auxiliary calendar table?
Why should I consider using an auxiliary numbers table?

 

 


Created: 2/4/2003 | Last Updated: 2/7/2006 | broken links | helpful | not helpful | statistics
© Copyright 2006, UBR, Inc. All Rights Reserved. (173)

 

Copyright 1999-2006, All rights reserved.
Finding content
Finding content.  An error has occured...