![](/img/trans.png)
[英]SQL-Server: How do I insert multiple rows with data from a temp table + store the ID of the inserted rows in the temp table
[英]How to insert rows from one temp table to another in sql
ID LogDate LogTime InoutMode
1 2017-02-23 19:30:00.0000000 1
2 2017-02-23 20:00:00.0000000 0
3 2017-02-23 20:30:00.0000000 1
4 2017-02-23 21:00:00.0000000 0
5 2017-02-23 21:30:00.0000000 1
6 2017-02-24 08:00:00.0000000 0
以上結果來自臨時表。現在我想將 LogTime 插入到另一個臨時表中,如下所示。
InOutMode-1 =>InTime
InOutMode-0 =>OutTime
InTime OutTime
19:30:00.0000000 20:00:00.0000000
20:30:00.0000000 21:00:00.0000000
21:30:00.0000000 08:00:00.0000000
要將一個表的行插入到另一個表中,您可以編寫以下 SQL 查詢:
INSERT INTO anotherTemp (InTime)
SELECT LogTime
FROM Temp
WHERE InoutMode = 1
INSERT INTO anotherTemp (OutTime)
SELECT LogTime
FROM Temp
WHERE InoutMode = 0
使用INSERT INTO .. SELECT FROM
構造像
insert into #temp2
select ID, LogDate,
case when InoutMode = 1 then LogTime end as InTime,
case when InoutMode = 0 then LogTime end as OutTime,
InoutMode
from #temp1
使用 2 個InoutMode
,一個用於InoutMode
和1
,另一個用於0
並根據Id
列或日期和時間列的順序給InoutMode
號。 然后加入這 2 個 cte。
詢問
;with cte as(
select [rn] = row_number() over(
order by [Id] -- also order by [LogDate], [LogTime]
), *
from #your_temp_table_name
where [InoutMode] = 1
),
cte2 as(
select [rn] = row_number() over(
order by [Id] -- also order by [LogDate], [LogTime]
), *
from #your_temp_table_name
where [InoutMode] = 0
)
select
t1.[LogTime] [InTime],
t2.[LogTime] [OutTime]
from cte t1
left join cte2 t2
on t1.[rn] = t2.[rn];
如果要將結果集放入新的臨時表中。 然后最后一部分可以修改為
select
t1.[LogTime] [InTime],
t2.[LogTime] [OutTime]
into #your_new_temp_table_name
from cte t1
left join cte2 t2
on t1.[rn] = t2.[rn];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.