2014-01-13 56 views
1

我試圖更新SQL數據庫中的一些預算數據。我有一個表,這是今年的數據集,另一個表包含去年(我需要插入今年的數據)。 在插入過程中,我需要爲臨時表中的每個站點編號創建一個唯一的行,每個站點編號需要是今年的信息(周編號,startdate,enddate等)。 我已經嘗試使用子查詢(但顯然這失敗了,因爲獲取站點編號的子查詢將返回多個記錄,所以我嘗試了一個cursor,但是,雖然它沒有錯誤,但它不會插入任何日期。任何人有那簡直太好了任何想法 這是我cursor codeSQL從子查詢中包含多行的2個表中插入

create table #tempSiteNoTable (SiteNo int) 
insert into #tempSiteNoTable 
Select distinct(SiteNumber) 
from Lynx_Period_Lookup 

    begin tran xxx 
    Declare @SiteNNo int 

    Declare SiteNumberCursor Cursor FOR 
     Select 
      SiteNo from #tempSiteNoTable where SiteNo = @SiteNNo 
     Open SiteNumberCursor 
    Fetch next from SiteNumberCursor 
    Into @SiteNNo while @@fetch_status = 0 

    begin 
     insert into Lynx_Period_Lookup 
      (SiteNumber,SubPeriod,StartDate,EndDate,[Year],Period,[Week],BusinessCalendarNumber,BusinessCalendarName) 
      Select 
      @SiteNNo, 
      SubPeriod, 
      StartDate, 
      EndDate, 
      2014 as year, 
      Period, 
      WeekNo, 
      BusinessCalendarNumber, 
      BusinessCalendarName 
      from accountingperiods 
      Fetch next from SiteNumberCursor 
      into @SiteNNo 

    End 
     Close SiteNumberCursor 
    Deallocate SiteNumberCursor 

回答

0

你應該能夠做到這一點沒有CURSOR - 和很容易,太

試試這個:!

CREATE TABLE #tempSiteNoTable (SiteNo int) 

INSERT INTO #tempSiteNoTable(SiteNo) 
    SELECT DISTINCT (SiteNumber) 
    FROM dbo.Lynx_Period_Lookup 

INSERT INTO dbo.Lynx_Period_Lookup(SiteNumber, SubPeriod, StartDate, EndDate, [Year], Period, [Week], BusinessCalendarNumber, BusinessCalendarName) 
    SELECT 
     t.SiteNo, 
     ap.SubPeriod, 
     ap.StartDate, 
     ap.EndDate, 
     2014 as year, 
     ap.Period, 
     ap.WeekNo, 
     ap.BusinessCalendarNumber, 
     ap.BusinessCalendarName 
    FROM 
     #tempSiteNoTable t 
    INNER JOIN 
     dbo.AccountingPeriods ap ON ... (how are those two sets of data related?)... 

唯一的一點我不知道 - AccountingPeriods#tempSiteNoTable如何相關 - 他們共享什麼常見列?

這一切就是這麼簡單 - 沒有光標,沒有與瞎搞行到痛苦的排(RBAR)處理 - 只有一個,漂亮,乾淨基於集合的聲明,你就大功告成了

0

我想你正在尋找CROSS JOIN;嘗試下面的代碼片段。

DECLARE @Table1 TABLE (Week int, StartDate datetime) 
DECLARE @Table2 TABLE (sitenumber int) 

INSERT INTO @Table1 (Week, StartDate) 
VALUES (1, '2014-01-01'), (2, '2014-01-08') 

INSERT INTO @Table2 (sitenumber) 
VALUES (1), (2) 

SELECT * 
FROM @Table1 CROSS JOIN @Table2