2011-11-28 72 views
2

我正在尋找一個解決方案如何,我可以在不同的表1000塊基於日期時間的部分,從一個大表移動行價值(作爲每月檔案)。我使用MS SQL Server 2008的移動SQL Server數據

萊姆斯Rusanu在塊移動行此處提供的計算器Move SQL Server data in limited (1000 row) chunks以下解決方案。像魅力一樣工作:-)

WHILE 1=1 
BEGIN 
    WITH messages AS (
    SELECT TOP 1000 id, messageDatetime, message 
     FROM DemoData) 
    DELETE messages 
     OUTPUT DELETED.id, messageDatetime, message 
     INTO messageArchive; 

    IF (@@ROWCOUNT = 0) 
     BREAK; 
END 

我現在需要的是能夠根據messageDate的月份部分將行移動到不同的表。從九月

  • 消息應該被插入到一個名爲messageArchive_09表十月
  • 消息應該被插入到一個名爲messageArchive_10
  • 表...

什麼想法?

回答

1

只是重複你有12倍的代碼使用month()不同的目標表中的WHERE子句和。我知道,複製和粘貼代碼感覺不好,替代方法是做一些事情dynamic。硬編碼是要走的路 -

WHILE 1=1 
BEGIN 
    WITH messages AS (
    SELECT TOP 1000 id, messageDatetime, message 
     FROM DemoData 
     WHERE month(messageDatetime) = 1) 
    DELETE messages 
     OUTPUT DELETED.id, DELETED.messageDatetime, DELETED.message 
     INTO messageArchive_01; 

    IF (@@ROWCOUNT = 0) 
     BREAK; 
END 

WHILE 1=1 
BEGIN 
    WITH messages AS (
    SELECT TOP 1000 id, messageDatetime, message 
     FROM DemoData 
     WHERE month(messageDatetime) = 2) 
    DELETE messages 
     OUTPUT DELETED.id, DELETED.messageDatetime, DELETED.message 
     INTO messageArchive_02; 

    IF (@@ROWCOUNT = 0) 
     BREAK; 
END 

一些代碼,如果你想要去的力度

declare @sql nvarchar(max) 
declare @Template nvarchar(max) =' 
WHILE 1=1 
BEGIN 
    WITH messages AS (
    SELECT TOP 1000 id, messageDatetime, message 
     FROM DemoData 
     WHERE month(messageDatetime) = <MONTH>) 
    DELETE messages 
     OUTPUT DELETED.id, DELETED.messageDatetime, DELETED.message 
     INTO <TABLENAME>; 

    IF (@@ROWCOUNT = 0) 
     BREAK; 
END' 

declare @I int = 1 

while @I <= 12 
begin 
    set @sql = replace(@Template, '<TABLENAME>', 'messageArchive_'+right([email protected], 2)) 
    set @sql = replace(@sql, '<MONTH>', @I) 

    exec (@sql) 

    set @I += 1 
end 
+0

+1使用。即使在動態SQL中,他也需要對翻譯值進行硬編碼,或者對每一行進行日期時間比較。 – JNK

相關問題