SQLServer数据库内容替换⽅法
在使⽤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] =sql语句替换表中内容
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 @ptr varbinary(16)
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 @ptr varbinary(16)
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两个表内容进⾏替换操作。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。