SQL Server數據庫內容替換方法
在使用iwms系統的過程中,我們會經常遇到數據內容的替換操作。在告訴大家如何替換數據內容之前,我建議大家先了解一下SQL Server數據庫的數據存儲類型:
SQL Server數據類型:
以上是數據庫的基礎知識,是做網站的朋友都應該知道的內容(無論你使用什么cms),所以建議大家都耐心看一下。
數據替換一般都發生在字符串數據字段中,除了ntext類型字段以外的其他字符串數據字段都可以使用以下的sql語句進行替換:
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 [數據表名] SET [字段名] = REPLACE([字段名],'老字符串','新字符串')
比如,替換iwms文章數據表(iwms_news)中的標題字段(title)的部分內容,我們應該這么寫:
UPDATE [iwms_news] SET [title] = REPLACE([title],'老字符串','新字符串')
上面的sql語句在iwms后臺的sql執行里面可以直接執行,基本上可以搞定所有的替換操作,但是由于ntext數據長度的原因,這一方法對ntext類型字段無效。那我們該用什么方法替換ntext類型字段的內容呢?方法有兩種:
一是類型轉換,將ntext類型轉換為varchar類型,然后再用replace。適合于單頁內容***長度<4000的文章。
update [數據表名] set [字段名] = replace(convert(varchar(4000), [字段名]),'老字符串','新字符串')
比如,替換iwms文章數據表(iwms_news)中的標題字段(content,ntext類型字段)的部分內容,我們應該這么寫:
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 [數據表名]
for read only
open wux_Cursor
fetch next from wux_Cursor into @ptr,@artId
while @@fetch_status=0
begin
select @Position=patindex('%老字符串%',[字段名]) from [數據表名] where [key字段名]=@artId
while @Position>0
begin
set @Position=@Position-1
updatetext [數據表名].[字段名] @ptr @Position @len '新字符串'
select @Position=patindex('%老字符串%',[字段名]) from [數據表名] where [key字段名]=@artId
end
fetch next from wux_Cursor into @ptr,@artId
end
close wux_cursor
deallocate wux_cursor
go
比如,替換iwms文章數據表(iwms_news)中的標題字段(content,ntext類型字段)的部分內容,我們應該這么寫
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查詢分析器中執行。
另外,由于iwms數據庫結構的問題,有分頁的文章內容需要先后對iwms_news和iwms_pages兩個表內容進行替換操作。
【編輯推薦】