[英]Copy data to temporary table from two different databases having same table in SQL
我有兩個數據庫。 一個數據庫有當年的數據,另一個有上一年的數據。
我想從名為tbl_Records
的表中將數據復制到臨時表中,該表在數據庫和臨時表中的數據中都可用。 我也使用了內連接。
select a.*
into #copy
from #temp t
inner join Records2021..tbl_Records r on t.uniqueno = r.uniqueno
where isdeleted = 0
表tbl_Records
有大約 150 列,並且所有列都是必需的。 因此首選*
現在我需要包含上一年的數據庫Records2020
。 我該怎么做?
使用 CTE 可能會有所幫助。 但問題是我需要為相同的列指定所有列名,這很乏味。 有沒有更簡單的方法可以做到這一點,因為我需要在不同表的近 50-60 個不同的存儲過程中實現這一點。
我的最終目標只是將兩個數據庫中的數據一起放入一個臨時表中。
代碼嘗試:
If object_id('tempdb..#copy') is not null
begin
drop table #copy
end
If object_id('tempdb..#temp') is not null
begin
drop table #temp
end;
with cte as
(
select a.*
from #temp t
inner join Records2021..tbl_Records r on t.uniqueno = r.uniqueno
where isdeleted = 0
union all
select a.*
from #temp t
inner join Records2020..tbl_Records r on t.uniqueno = r.uniqueno
where isdeleted = 0
)
select a.*
into #copy
from cte /*this does not work as I need to mention all 150 columns here.*/
我也對任何其他選擇持開放態度。
DBMS:微軟 SQL 服務器
您可以使用UNION ALL
解決它,但請注意#temp
和tbl_Records
表必須具有相同的結構(列和數據類型)。
SELECT
*
INTO
#copy
FROM (
SELECT *
FROM #temp
UNION ALL
SELECT *
FROM [Records2021]..[tbl_Records]
) AS tbl
WHERE
tbl.isdeleted = 0
如果表結構不同,請對一張表使用SELECT... INTO
,並為第二張表調整INSERT INTO
所需的列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.