SQL Server数据库内容替换方法 |
|
本文标签:SQLServer 数据库 数据类型 存储过程 在使用iwms系统的过程中,我们会经常遇到数据内容的替换操作 。在告诉大家如何替换数据内容之前,我建议大家先了解一下SQL Server数据库的数据存储类型: SQL Server数据类型: 以上是数据库的基础知识,是做网站的朋友都应该知道的内容(无论你使用什么cms),所以建议大家都耐心看一下 。 数据替换一般都发生在字符串数据字段中,除了ntext类型字段以外的其他字符串数据字段都可以使用以下的sql语句进行替换:
UPDATE [数据表名] SET [字段名] = REPLACE([字段名],老字符串,新字符串) UPDATE [iwms_news] SET [title] = REPLACE([title],老字符串,新字符串) 一是类型转换,将ntext类型转换为varchar类型,然后再用replace 。适合于单页内容最大长度<4000的文章 。 update [数据表名] set [字段名] = replace(convert(varchar(4000), [字段名]),老字符串,新字符串) 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两个表内容进行替换操作 。 |