从连接SQL Server创建表

时间:2015-04-26 19:03:44

标签: sql-server join

我正在运行查询:

select 
    [temp_table_excel_insert_for_join].person_id,
    [temp_table_excel_insert_for_join].city,
    city.city_id
from 
    temp_table_excel_insert_for_join, city
where 
    temp_table_excel_insert_for_join.city = city.city

现在没有问题我希望将所有这些列作为新表,所以我使用了

create table mytable as 
( select 
      [temp_table_excel_insert_for_join].person_id,
      [temp_table_excel_insert_for_join].city,
      city.city_id
  from 
      temp_table_excel_insert_for_join, city
  where 
      temp_table_excel_insert_for_join.city=city.city)

但它对我不起作用我该怎么做才能实现呢?我不想创建一个我想要一张桌子的视图。但是我不熟悉我是否应该进行左连接或其他事情

3 个答案:

答案 0 :(得分:1)

如果您的目标是使用mytable列创建新表person_id, city, city_id,请使用select ... into语法:

select 
    [temp_table_excel_insert_for_join].person_id,
    [temp_table_excel_insert_for_join].city,
    city.city_id
into 
    mytable 
from 
    temp_table_excel_insert_for_join
inner join 
    city on temp_table_excel_insert_for_join.city = city.city

请注意,如果您多次运行它会失败,因为该表已经存在,您必须先删除它。

See the documentation for more information on the into clause

答案 1 :(得分:1)

试试这个

select [temp_table_excel_insert_for_join].person_id
       , [temp_table_excel_insert_for_join].city
       ,city.city_id
  into mytable 
  from temp_table_excel_insert_for_join inner join city on temp_table_excel_insert_for_join.city=city.city)

答案 2 :(得分:0)

尝试分离这两个操作。第一:

CREATE TABLE MyTable ( etc)

然后

INSERT INTO MyTable ( <List of columns to insert> )
SELECT <Columns to insert>
FROM etc
WHERE etc