程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> 更多數據庫知識 >> 如何替換SQL Server數據庫內容

如何替換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 @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兩個表內容進行替換操作。

原文:http://edu.itbulo.com/200904/125440.htm

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved