1. 程式人生 > 其它 >MSSQL Server資料庫內容替換方法

MSSQL Server資料庫內容替換方法

技術標籤:綜合

本篇文章由泉州SEOwww.234yp.com 整理髮布,php連線mssqlwww.234yp.com/Article/168189.html謝謝合作!
php連線mssql

  在使用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欄位名][email protected]
  while @Position>0
  begin
  set @[email protected]
  updatetext [資料表名].[欄位名] @ptr @Position @len '新字串'
  select @Position=patindex('%老字串%',[欄位名]) from [資料表名] where [key欄位名][email protected]
  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][email protected]
  while @Position>0
  begin
  set @[email protected]
  updatetext iwms_news.[content] @ptr @Position @len '新字串'
  select @Position=patindex('%老字串%',[content]) from iwms_news where [articleid][email protected]
  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兩個表內容進行替換操作。


關於更多php連線mssql內容,可以收藏本網頁。
體育直播吧是中國知名的體育入口網站