SQL Server數(shù)據(jù)庫內(nèi)容替換方法
在使用iwms系統(tǒng)的過程中,我們會經(jīng)常遇到數(shù)據(jù)內(nèi)容的替換操作。在告訴大家如何替換數(shù)據(jù)內(nèi)容之前,我建議大家先了解一下SQL Server數(shù)據(jù)庫的數(shù)據(jù)存儲類型:
SQL Server數(shù)據(jù)類型:
以上是數(shù)據(jù)庫的基礎(chǔ)知識,是做網(wǎng)站的朋友都應(yīng)該知道的內(nèi)容(無論你使用什么cms),所以建議大家都耐心看一下。
數(shù)據(jù)替換一般都發(fā)生在字符串?dāng)?shù)據(jù)字段中,除了ntext類型字段以外的其他字符串?dāng)?shù)據(jù)字段都可以使用以下的sql語句進(jìn)行替換:
update [swf_Upload] set [Dir] = replace([Dir],'200901/14','200901/15') update [swf_Content] set [Description] = replace([Description],'200901/14','200901/15') update [swf_Content_01] set [content] = replace(convert(varchar(4000), [content]),'200901/14','200901/15') |
UPDATE [數(shù)據(jù)表名] SET [字段名] = REPLACE([字段名],'老字符串','新字符串')
比如,替換iwms文章數(shù)據(jù)表(iwms_news)中的標(biāo)題字段(title)的部分內(nèi)容,我們應(yīng)該這么寫:
UPDATE [iwms_news] SET [title] = REPLACE([title],'老字符串','新字符串')
上面的sql語句在iwms后臺的sql執(zhí)行里面可以直接執(zhí)行,基本上可以搞定所有的替換操作,但是由于ntext數(shù)據(jù)長度的原因,這一方法對ntext類型字段無效。那我們該用什么方法替換ntext類型字段的內(nèi)容呢?方法有兩種:
一是類型轉(zhuǎn)換,將ntext類型轉(zhuǎn)換為varchar類型,然后再用replace。適合于單頁內(nèi)容***長度<4000的文章。
update [數(shù)據(jù)表名] set [字段名] = replace(convert(varchar(4000), [字段名]),'老字符串','新字符串')
比如,替換iwms文章數(shù)據(jù)表(iwms_news)中的標(biāo)題字段(content,ntext類型字段)的部分內(nèi)容,我們應(yīng)該這么寫:
update iwms_news set [content] = replace(convert(varchar(4000),[content]),'老字符串','新字符串')
二是SQL Server存儲過程
declare @artId int
declare @Position int,@len int
set @len = datalength('老字符串')
declare wux_Cursor scroll Cursor
for
select textptr([字段名]),[key字段名] from [數(shù)據(jù)表名]
for read only
open wux_Cursor
fetch next from wux_Cursor into @ptr,@artId
while @@fetch_status=0
begin
select @Position=patindex('%老字符串%',[字段名]) from [數(shù)據(jù)表名] where [key字段名]=@artId
while @Position>0
begin
set @Position=@Position-1
updatetext [數(shù)據(jù)表名].[字段名] @ptr @Position @len '新字符串'
select @Position=patindex('%老字符串%',[字段名]) from [數(shù)據(jù)表名] where [key字段名]=@artId
end
fetch next from wux_Cursor into @ptr,@artId
end
close wux_cursor
deallocate wux_cursor
go
比如,替換iwms文章數(shù)據(jù)表(iwms_news)中的標(biāo)題字段(content,ntext類型字段)的部分內(nèi)容,我們應(yīng)該這么寫
declare @artId int
declare @Position int,@len int
set @len = datalength('老字符串')
declare wux_Cursor scroll Cursor
for
select textptr([content]),[articleid] from iwms_news
for read only
open wux_Cursor
fetch next from wux_Cursor into @ptr,@artId
while @@fetch_status=0
begin
select @Position=patindex('%老字符串%',[content]) from iwms_news where [articleid]=@artId
while @Position>0
begin
set @Position=@Position-1
updatetext iwms_news.[content] @ptr @Position @len '新字符串'
select @Position=patindex('%老字符串%',[content]) from iwms_news where [articleid]=@artId
end
fetch next from wux_Cursor into @ptr,@artId
end
close wux_cursor
deallocate wux_cursor
go
ok了,需要注意的是:存儲過程只能在SQL Server查詢分析器中執(zhí)行。
另外,由于iwms數(shù)據(jù)庫結(jié)構(gòu)的問題,有分頁的文章內(nèi)容需要先后對iwms_news和iwms_pages兩個表內(nèi)容進(jìn)行替換操作。
【編輯推薦】