在创建临时表并像这样声明数据类型之后;

CREATE TABLE #TempTable(
ID int,
Date datetime,
Name char(20))

然后,我如何插入已经在数据库中的物理表上持有的相关数据?


当前回答

insert into #temptable (col1, col2, col3)
select col1, col2, col3 from othertable

注意,这被认为是糟糕的做法:

insert into #temptable 
select col1, col2, col3 from othertable

如果临时表的定义要更改,则代码可能在运行时失败。

其他回答

我提供了两种方法来解决同一个问题,

解决方案1:这种方法包括2步,首先创建一个临时表 指定的数据类型,然后从现有数据中插入值 表格

CREATE TABLE #TempStudent(tempID  int, tempName  varchar(MAX) )
INSERT INTO #TempStudent(tempID, tempName) SELECT id, studName FROM students where id =1

SELECT * FROM #TempStudent

解决方案2:这种方法很简单,您可以直接将值插入到 临时表,由系统自动创建 与原始表具有相同数据类型的临时表。

SELECT id, studName  INTO #TempStudent FROM students where id =1

SELECT * FROM #TempStudent

正确的查询:

drop table #tmp_table

select new_acc_no, count(new_acc_no) as count1
into #tmp_table
from table
where unit_id = '0007' 
group by unit_id, new_acc_no
having count(new_acc_no) > 1
insert #temptable
select idfield, datefield, namefield from yourrealtable
SELECT * 
INTO #TempTable
FROM table
INSERT INTO #TempTable (ID, Date, Name) 
SELECT id, date, name 
FROM physical_table