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

sql:如何从一个表中插入数据并将其输出到一个临时表中,同时从第一个表中获得额外的值

  •  0
  • LittleFunny  · 技术社区  · 7 年前

    我可以用 OUTPUT INSERT语句的关键字,用于将新数据插入表并输出到临时表。

    要插入到另一个表中的输入表有一个id,我需要传递给临时表,而不是要插入的表。此临时表稍后将不得不用于对另一个表进行额外插入。

    INSERT INTO table1 (Name, Age)
    OUTPUT inserted.Id, User.Id (??) INTO TemporaryTable
    SELECT Name, Age FROM User
    

    有办法吗?因为下一次插入将需要新的 table1.Id User.Id ,所以我可以迁移一些数据。

    2 回复  |  直到 7 年前
        1
  •  2
  •   sunnykachwala    7 年前

    不用临时表,可以使用变量,这样就不会占用更多内存。

    create table table1 
    (
    id int NOT NULL,
    ,name varchar(50)
    ,age int,
     PRIMARY KEY (id)
    )
    
    insert into table1 (name,age) values ('name', 10)                          
    
    declare @extracolumn as int =  scope_identity() 
    select @extracolumn 
    

    在下一个插入操作中使用这个@extracolumn。

        2
  •  1
  •   Sharad Venkataraman    7 年前

    临时表的架构中是否包含额外的列?

    create table table1 
    (
    id int
    ,name varchar(50)
    ,age int
    )
    
    declare @TemporaryTable table -- or Create table #TemporaryTable
    (                             
      id int,                     
      userid int -- defining the extra column                 
    );                            
    
    declare @extracolumn as int = 100; 
    -- or declare @extracolumn as int = (select value from table where condition)
    -- note that subqueries cannot be added directly in the output clause
    -- so need to declare and set a variable that holds the value
    
    insert into table1
    output  inserted.id,@extracolumn into  @TemporaryTable -- or #TemporaryTable
    values(1,'name',10)
    
    select * from @TemporaryTable
    

    输出为

    id  userid
    1   100