在SQL Server中,可以使用insert将行插入到表中。。SELECT语句:

INSERT INTO Table (col1, col2, col3)
SELECT col1, col2, col3 
FROM other_table 
WHERE sql = 'cool'

是否也可以使用SELECT更新表?我有一个包含这些值的临时表,并希望使用这些值更新另一个表。也许是这样的:

UPDATE Table SET col1, col2
SELECT col1, col2 
FROM other_table 
WHERE sql = 'cool'
WHERE Table.id = other_table.id

当前回答

甚至还有一种更短的方法,可能会让你感到惊讶:

示例数据集:

CREATE TABLE #SOURCE ([ID] INT, [Desc] VARCHAR(10));
CREATE TABLE #DEST   ([ID] INT, [Desc] VARCHAR(10));

INSERT INTO #SOURCE VALUES(1,'Desc_1'), (2, 'Desc_2'), (3, 'Desc_3');
INSERT INTO #DEST   VALUES(1,'Desc_4'), (2, 'Desc_5'), (3, 'Desc_6');

代码:

UPDATE #DEST
SET #DEST.[Desc] = #SOURCE.[Desc]
FROM #SOURCE
WHERE #DEST.[ID] = #SOURCE.[ID];

其他回答

我以前使用过INSERT SELECT。对于那些想使用新东西的人来说,这里有一个类似的解决方案,但它要短得多:

UPDATE table1                                          // Table that's going to be updated.
LEFT JOIN                                              // Type of join.
    table2 AS tb2                                      // Second table and rename for easy.
ON
    tb2.filedToMatchTables = table1.fieldToMatchTables // Fields to connect both tables.
SET
    fieldFromTable1 = tb2.fieldFromTable2;             // Field to be updated on table1.

    field1FromTable1 = tb2.field1FromTable2,           // This is in the case you need to
    field1FromTable1 = tb2.field1FromTable2,           // update more than one field.
    field1FromTable1 = tb2.field1FromTable2;           // Remember to put ; at the end.

declare @tblStudent table (id int,name varchar(300))
declare @tblMarks table (std_id int,std_name varchar(300),subject varchar(50),marks int)

insert into @tblStudent Values (1,'Abdul')
insert into @tblStudent Values(2,'Rahim')

insert into @tblMarks Values(1,'','Math',50)
insert into @tblMarks Values(1,'','History',40)
insert into @tblMarks Values(2,'','Math',30)
insert into @tblMarks Values(2,'','history',80)


select * from @tblMarks

update m
set m.std_name=s.name
 from @tblMarks as m
left join @tblStudent as s on s.id=m.std_id

select * from @tblMarks

如果您使用的是SQL Server,则可以在不指定联接的情况下从另一个表更新一个表,并且只需从where子句链接这两个表。这使得SQL查询更加简单:

UPDATE Table1
SET Table1.col1 = Table2.col1,
    Table1.col2 = Table2.col2
FROM
    Table2
WHERE
    Table1.id = Table2.id

使用别名:

UPDATE t
   SET t.col1 = o.col1
  FROM table1 AS t
         INNER JOIN 
       table2 AS o 
         ON t.id = o.id

我添加这个只是为了让你可以看到一个快速的方法来编写它,这样你就可以在更新之前检查将要更新的内容。

UPDATE Table 
SET  Table.col1 = other_table.col1,
     Table.col2 = other_table.col2 
--select Table.col1, other_table.col,Table.col2,other_table.col2, *   
FROM     Table 
INNER JOIN     other_table 
    ON     Table.id = other_table.id