2015-11-05 62 views
0

我插入批量的記錄如何從插入的表中獲取所有這些ID。如何從插入的表中獲取所有的ID

我想用所有的ID作爲forgein鍵,並插入到另一個表

INSERT INTO [dbo].[BudCustomers] 
      ([LegalName] 
      ,[EffectiveDate] 
      ,[LawsonCustomerNumber] 
      ,[ChangeReason] 
      ,[ImportedRecord] 
      ,[VersionID] 
      ,[StatusID] 
      ,[CreatedDate] 
      ,[CreatedUserID] 
      ,[LastModifiedDate] 
      ,[LastModifiedUserID] 
      ,[CustomerGroupID]) 
SELECT CustomerName 
     ,'1900-01-01 00:00:00.000' 
     , CASE WHEN PATINDEX('%[0-9]%', CustomerName) > 0 
      THEN REPLACE(SUBSTRING(CustomerName, PATINDEX('%[0-9]%', CustomerName), 
      LEN(CustomerName)), ')', '') 
      ELSE 0 END 
     ,'' 
     ,1 
     ,1 
     ,1 
     ,GETDATE() 
     ,'Import' 
     ,GETDATE() 
     ,'Import' 
     ,NULL 
FROM External_Blk_Itm_Contracts 
WHERE TerminalName NOT IN (SELECT MBFTERMINALNAME FROM budterminals) 
+4

我認爲這些ID標識值?最好的方法是使用OUTPUT子句。 https://msdn.microsoft.com/en-us/library/ms177564.aspx –

+0

INSERT INTO ... OUTPUT col_name INTO #temp_table SELECT ...' – lad2025

+0

如何在此查詢中執行此操作 – user1030181

回答

3

使用OUTPUT條款:

CREATE TABLE #temp (CustomerId <datatype>); 

INSERT INTO [dbo].[BudCustomers] 
      ([LegalName] 
      ,[EffectiveDate] 
      ,[LawsonCustomerNumber] 
      ,[ChangeReason] 
      ,[ImportedRecord] 
      ,[VersionID] 
      ,[StatusID] 
      ,[CreatedDate] 
      ,[CreatedUserID] 
      ,[LastModifiedDate] 
      ,[LastModifiedUserID] 
      ,[CustomerGroupID]) 
OUTPUT inserted.CustomerId 
INTO #temp 
SELECT CustomerName 
     ,'1900-01-01 00:00:00.000' 
     , CASE 
      WHEN PATINDEX('%[0-9]%', CustomerName) > 0 
      THEN REPLACE(SUBSTRING(CustomerName, PATINDEX('%[0-9]%', CustomerName), 
      LEN(CustomerName)), ')', '') ELSE 0 END 
     ,'' 
     ,1 
     ,1 
     ,1 
     ,GETDATE() 
     ,'Import' 
     ,GETDATE() 
     ,'Import' 
     ,NULL 
FROM External_Blk_Itm_Contracts 
WHERE TerminalName NOT IN (SELECT MBFTERMINALNAME FROM budterminals) 

SELECT * 
FROM #temp; 
+0

does not work this above查詢 – user1030181

+1

你能更具體嗎?可能是'inserted.CustomerId'我更新了回答 – lad2025

+1

你正在運行哪個版本的SQL Server? – shawnt00