2013-12-09 43 views
0

我的問題是與@officeident。對於插入到LicenseHolder中的每條新記錄,它具有相同的officeident ..此SQL插入OfficeID,每行的值爲1495。這是插入的最後一個身份。哪些不會創建父子關係。插入父表和子表

我想我應該研究下一個遊標。對於插入到Office的每個插入,然後將新行添加到LicenseHolder,以便我可以建立關係。或者,如果有更簡單的方法或任何幫助將不勝感激。

DECLARE @officeident INT 

insert into [MembersDB].[dbo].[Office] 
([AddressLine1] 
,[AddressLine2] 
,[State] 
,[PostCode]) 
select [OfficeMailingAddr],[OfficeMailingAddr],[state],'1' FROM [Members].[dbo].[Main] 
SET @officeident = SCOPE_IDENTITY() 

INSERT INTO [MembersDB].[dbo].[LicenseHolder] ([Name] 
    ,[Email] 
    ,[Mobile] 
    ,[OfficeNumber] 
    ,[LicenseHolderTypeID] 
    ,[PartyTypeID] 
    ,[OfficeID]) 

SELECT 
    [OfficeOf] 
    ,[OfficeEmail] 
    ,[Phone] 
    ,'1234' 
    ,'1' 
    ,'1' 
    ,@officeident  --I want like this to be different for each row. 
FROM [Members].[dbo].[Main] 

回答

0

嘗試類似這樣的東西。我把它寫在了我的頭頂,所以你可能需要調試:

基本上,我在這裏寫了一個遊標,它循環遍歷你要用來插入新表的表的結果。然後一次創建2個新插入記錄...(然後對MAIN表中的下一個結果行執行相同操作)。

DECLARE @OfficeMailingAddr as varchar(254), @OfficeMailingAddr as varchar(254), @state as varchar(254), @Name as varchar(254), @Email as varchar(254), @Mobile as varchar(254), @Phone as varchar(254) 

declare NewCursor Cursor for 
SELECT [OfficeMailingAddr],[OfficeMailingAddr],[state], [Name] 
    ,[Email] 
    ,[Mobile] 
    ,[OfficeNumber] FROM [Members].[dbo].[Main] 

open NewCursor 
fetch next from NewCursor into @OfficeMailingAddr, @OfficeMailingAddr, @state, @Name, @Email, @Mobile, @Phone 
WHILE @@FETCH_STATUS = 0 
begin 

    insert into [MembersDB].[dbo].[Office] 
([AddressLine1] 
,[AddressLine2] 
,[State] 
,[PostCode]) VALUES (@OfficeMailingAddr, @OfficeMailingAddr, @state,'1') 
SET @officeident = SCOPE_IDENTITY() 

INSERT INTO [MembersDB].[dbo].[LicenseHolder] ([Name] 
    ,[Email] 
    ,[Mobile] 
    ,[OfficeNumber] 
    ,[LicenseHolderTypeID] 
    ,[PartyTypeID] 
    ,[OfficeID]) VALUES (@Name, @Email, @Mobile, @Phone,'1234' 
    ,'1' 
    ,'1' 
    ,@officeident) 

FETCH NEXT FROM NewCursor INTO @OfficeMailingAddr, @OfficeMailingAddr, @state, @Name, @Email, @Mobile, @Phone 
END 

Close NewCursor 
deallocate NewCursor