代码之家  ›  专栏  ›  技术社区  ›  Vishal

我可以从一个表中选择一组行,并将其直接插入到一个表或SQL中的同一个表中吗?

  •  3
  • Vishal  · 技术社区  · 15 年前

    嗨,我只是好奇我能不能做点什么-

    insert into Employee ( Select * from Employee where EmployeeId=1)
    

    我只是觉得需要做很多次……所以只是好奇是否有任何方法可以实现它。

    3 回复  |  直到 15 年前
        1
  •  7
  •   Peter Lang    15 年前

    你可以这样做,但你不能 Select * 如果要更改列值:

    Insert into employee ( employeeId, someColumn, someOtherColumn )
      Select 2, someColumn, someOtherColumn
      From employee
      Where employeeId=1
    

    这将插入 2 作为你的新 employeeId .

        2
  •  3
  •   SQLMenace    15 年前

    是的,列出来然后这样做

    insert into Employee (EmployeeId, LastName, FirstName......)
    Select 600 as EmployeeId, LastName, FirstName......
    from Employee where EmployeeId=1
    

    但是,如果EmployeeID是标识列,则还需要执行以下操作

    set identity_insert employee on 
    

    先然后

    set identity_insert employee off 
    

    做完之后

        3
  •  3
  •   SWeko    15 年前

    你可以用 INSERT INTO ... SELECT ... 语法:如果目标表已经存在,并且您只想向其追加行。通过只执行 SELECT 部分。

    Insert into existingTable ( Column1, Column2, Column3, ... )
    Select 1, Column2, Column3
    From tableName
    Where ....
    

    您不受简单选择的限制, 选择 语句可以根据需要进行复杂化。另外,您不需要为所选列提供名称,因为它们将由目标表提供。 但是,如果在dest表上有autoincrement列,则可以从 INSERT 的列列表或使用 set identity_insert '配置。

    如果要从现有数据创建新表,则应使用 SELECT ... INTO ... 句法

    Select 1 as Column1, Column2, Column3
    Into newTable
    From tableName
    Where ....
    

    同样,select可以是任意复杂的,但是,由于列名称取自select语句,所以所有列都必须具有显式名称。如果“newtable”表已经存在,此语法将给出一个错误。如果您想快速复制一张表来尝试某项操作,此表单非常方便。