簡體   English   中英

插入帶有子查詢的臨時表

[英]INSERT INTO temp table with subquery

我試圖插入到臨時表與insert into....select 我當前的語句如下所示:

insert into ods.account
(
  AccountNumber,
  AccountName,
  AccountCreated,
  AccountEnded,
  PayoffDate
)
select
  AccountNumber
  , AccountName
  , AccountCreated
  , AccountEnded
  , PayoffDate 
from dbo.InsuranceAccount

我希望能夠將此信息放入臨時表中,如果可能的話,我想在SQL Server中查詢頂部插入臨時表中。

您可以簡單地執行以下操作:

select
  AccountNumber
  , AccountName
  , AccountCreated
  , AccountEnded
  , PayoffDate into #myTempTable
from dbo.InsuranceAccount

或者您可以先創建臨時表,然后執行插入操作:

create table #tempTable(AccountName varchar(100), AccountNumber int)-- so on..
insert into #tempTable(AccountName, AccountNumber)
select AccountName, AccountNumber from dbo.InsuranceAccount

使用SQL中的臨時表可以通過幾種方法進行此操作。

如果您只是想將選擇內容插入到臨時表中,請使用以下方法。 請記住,您不能在循環中使用它,因為每次選擇運行時它都會創建臨時表:

select
  AccountNumber
  , AccountName
  , AccountCreated
  , AccountEnded
  , PayoffDate 
into #temp_table      
from dbo.InsuranceAccount

您還可以預定義臨時表,然后像其他任何表一樣使用INSERT INTO 此方法很好,因為您可以在WHILE循環中使用這種臨時表,並在每個循環中插入數據。

create table #temp_table
(
  field1 int not null,
  field2 char(1),
  ...
)

insert into #temp_table
select 
  AccountNumber
  , AccountName
  , AccountCreated
  , AccountEnded
  , PayoffDate      
from dbo.InsuranceAccount

這可能會有所幫助。

IF OBJECT_ID('temp..#InsuranceAccount') IS NOT NULL
BEGIN
    DROP TABLE #InsuranceAccount
END

SELECT  AccountNumber
      , AccountName
      , AccountCreated
      , AccountEnded
      , PayoffDate 
INTO  #InsuranceAccount
FROM dbo.InsuranceAccount

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM