t-sql replace on text field

不想你离开。 提交于 2019-11-30 04:24:46

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

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>

This is my code snippet for this scenario:

DECLARE @oldtext    varchar(1000)
DECLARE @newtext    varchar(1000)
DECLARE @textlen    int
DECLARE @ptr        binary(16)
DECLARE @pos        int
DECLARE @id         uniqueidentifier

SET @oldtext = 'oldtext'
SET @newtext = 'newtext'
SET @textlen = LEN(@oldtext)

DECLARE mycursor CURSOR LOCAL FAST_FORWARD
FOR
    SELECT  [UniqueID]
            ,TEXTPTR([Text])
            ,CHARINDEX(@oldtext, [Text]) - 1
    FROM    [dbo].[myTable] 
    WHERE   [Text] LIKE '%' + @oldtext +'%'

OPEN mycursor

FETCH NEXT FROM mycursor into @id, @ptr, @pos

WHILE @@fetch_status = 0
BEGIN   
    UPDATETEXT [dbo].[myTable].Text @ptr @pos @textlen @newtext

    FETCH NEXT FROM mycursor into @id, @ptr, @pos   
END

CLOSE mycursor
DEALLOCATE mycursor

You would have to cast the text field to a varchar(8000) or nvarchar(4000) if you are replacing over an ntext field.

MyField = REPLACE(CAST(MyField as VARCHAR(4000)), "string1", "string2")

This ofcourse will only work if you can guarantee the content in the field is <= 4000/8000 characters in length.

You can also use the SUBSTRING() function, which returns a varchar when passed a text value.

For instance:

MyVarchar = SUBSTRING(myTextField, 1, DATALENGTH(myTextField))

If you're populating a varchar with a specific length, you can truncate to fit:

MyVarchar100 = SUBSTRING(myTextField, 1, 100)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!