[英]Copy data to temporary table from two different databases having same table in SQL
I have two databases.我有两个数据库。 One database has current year data and the other has previous year data.一个数据库有当年的数据,另一个有上一年的数据。
I want to copy data into a temporary table from a table named tbl_Records
which is available in both databases and data from a temporary table.我想从名为tbl_Records
的表中将数据复制到临时表中,该表在数据库和临时表中的数据中都可用。 I have used inner join for the same.我也使用了内连接。
select a.*
into #copy
from #temp t
inner join Records2021..tbl_Records r on t.uniqueno = r.uniqueno
where isdeleted = 0
The table tbl_Records
has around 150 columns and all columns are required.表tbl_Records
有大约 150 列,并且所有列都是必需的。 Hence preferred *
因此首选*
Now I need to include the database Records2020
for the previous year.现在我需要包含上一年的数据库Records2020
。 How can I do so?我该怎么做?
Using a CTE may help.使用 CTE 可能会有所帮助。 But the issue is I need to specify all column names for the same which is tedious.但问题是我需要为相同的列指定所有列名,这很乏味。 Is there an easier way to do this as I need to implement this in almost 50-60 different stored procedures for different tables.有没有更简单的方法可以做到这一点,因为我需要在不同表的近 50-60 个不同的存储过程中实现这一点。
My ultimate goal is just to get data from both databases together into one temporary table.我的最终目标只是将两个数据库中的数据一起放入一个临时表中。
Code attempt:代码尝试:
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.*/
I'm open to any other alternatives too.我也对任何其他选择持开放态度。
DBMS: Microsoft SQL Server DBMS:微软 SQL 服务器
You can solve it using UNION ALL
but pay attention that #temp
and tbl_Records
table must have the same structure (columns and data type).您可以使用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
If table structure is different, use SELECT... INTO
for one table, and for the second table adjust INSERT INTO
with needed columns.如果表结构不同,请对一张表使用SELECT... INTO
,并为第二张表调整INSERT INTO
所需的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.