在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

当前回答

在接受的答案中,在以下内容之后:

SET
Table_A.col1 = Table_B.col1,
Table_A.col2 = Table_B.col2

我想补充一句:

OUTPUT deleted.*, inserted.*

我通常做的是将所有内容放入回滚事务中,并使用“OUTPUT”:这样我就可以看到即将发生的一切。当我对所看到的感到满意时,我将ROLLBACK更改为COMMIT。

我通常需要记录我所做的事情,所以我在运行回滚查询时使用“results to Text”选项,并保存脚本和OUTPUT的结果。(当然,如果我更改了太多行,这是不可行的)

其他回答

SQLite3对我很有用,在INNER SELECT之后用SELECT更新行。

UPDATE clients
SET col1 = '2023-02-02 18:51:30.826621'
FROM (
      SELECT * FROM clients dc WHERE dc.phone NOT IN (
               SELECT do.phone FROM dclient_order do WHERE do.order_date > '2023-01-01' GROUP BY do.phone
               )
      ) NewTable
WHERE clients.phone = NewTable.phone;
UPDATE
    Table_A
SET
    Table_A.col1 = Table_B.col1,
    Table_A.col2 = Table_B.col2
FROM
    Some_Table AS Table_A
    INNER JOIN Other_Table AS Table_B
        ON Table_A.id = Table_B.id
WHERE
    Table_A.col3 = 'cool'
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

单向

UPDATE t 
SET t.col1 = o.col1, 
    t.col2 = o.col2
FROM 
    other_table o 
  JOIN 
    t ON t.id = o.id
WHERE 
    o.sql = 'cool'
UPDATE table1
SET column1 = (SELECT expression1
               FROM table2
               WHERE conditions)
[WHERE conditions];

使用SQL Server中另一个表中的数据更新一个表时UPDATE语句的语法。