如何在 SQL Server 2008 中使用表别名编写 UPDATE SQL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4981481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:18:55  来源:igfitidea点击:

How to write UPDATE SQL with Table alias in SQL Server 2008?

sqlsql-serversql-server-2008sql-updatealias

提问by javauser71

I have a very basic UPDATE SQL-

我有一个非常基本的UPDATE SQL-

UPDATE HOLD_TABLE Q SET Q.TITLE = 'TEST' WHERE Q.ID = 101;

This query runs fine in Oracle, Derby, MySQL- but it fails in SQL server 2008with following error:

此查询在Oracle, Derby, 中运行良好MySQL- 但在 SQL Server 2008 中失败并出现以下错误:

"Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'Q'."

“消息 102,级别 15,状态 1,第 1 行 'Q' 附近的语法不正确。”

If I remove all occurrences of the alias, "Q" from SQL then it works.

如果我从 SQL 中删除所有出现的别名“Q”,那么它就可以工作了。

But I need to use the alias.

但我需要使用别名。

回答by Mark Byers

The syntax for using an alias in an update statement on SQL Server is as follows:

在 SQL Server 上的更新语句中使用别名的语法如下:

UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;

The alias should not be necessary here though.

不过这里不需要别名。

回答by Ryk

You can always take the CTE, (Common Tabular Expression), approach.

您始终可以采用CTE(通用表格表达式)方法。

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';