首页 > 解决方案 > 来自 Select 的 SQL 更新

问题描述

update table1 
set month =  x

    select FORMAT(getdate(), 'MMM yyyy') x
    from table1 
    where currenmonth >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
     and currentmonth < datefromparts(year(getdate()), month(getdate()), 1) 

我收到一个错误:

列名“x”无效

不知道为什么我会收到这个错误。需要帮忙。谢谢。

标签: sqlsql-server

解决方案


这甚至不是一个正确的查询。

检查此示例(来自https://chartio.com/resources/tutorials/how-to-update-from-select-in-sql-server/):

UPDATE
  books
SET
  books.primary_author = authors.name
FROM
  books
INNER JOIN
  authors
ON
  books.author_id = authors.id
WHERE
  books.title = 'The Hobbit'

所以你的查询应该是......

update table1
set month = FORMAT(getdate(), 'MMM yyyy')
from table1 
     where   
         currenmonth >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
         and currentmonth < datefromparts(year(getdate()), month(getdate()), 1) 

推荐阅读