是否可以使用 Sql MERGE 语法从另一个变量表更新/插入数据?
我希望插入
或更新
表中的一行 - 所以我希望尝试使用MERGE 语法。我的问题是我的数据(插入/更新)存在于变量表中。我不确定如何为插入/更新部分编写正确的语法。
这是我的伪代码:-
-- Here's the Variable Table ... and not it has not PK.
DECLARE @PersonId INTEGER
DECLARE @variableTable TABLE (
@SomeScore DECIMAL(10,7),
@SomeAverage DECIMAL(10,7),
@SomeCount INTEGER)
-- Insert or Update
MERGE INTO SomeTable
WHERE PersonId = @PersonId
WHEN MATCHED THEN
UPDATE
SET PersonScore = ??????????
PersonAverage = ???????
PersonCount = ????????
WHEN NOT MATCHED THEN
INSERT(PersonId, PersonScore, PersonAverage, PersonCount)
VALUES(@PersonId, ????, ?????, ????)
..并且我不确定如何确保 UPDATE
正确地仅更新 1 行(即...是否需要 WHERE
子句?)
最后,我的这篇文章基于这个SO问题。
I wish to Insert
or Update
a row in a table - so I wish to try and use the MERGE syntax. My problem is that my data (to insert/update) exists in a variable table
. I'm not sure how to write the correct syntax for the insert/update part.
Here's my pseduo code :-
-- Here's the Variable Table ... and not it has not PK.
DECLARE @PersonId INTEGER
DECLARE @variableTable TABLE (
@SomeScore DECIMAL(10,7),
@SomeAverage DECIMAL(10,7),
@SomeCount INTEGER)
-- Insert or Update
MERGE INTO SomeTable
WHERE PersonId = @PersonId
WHEN MATCHED THEN
UPDATE
SET PersonScore = ??????????
PersonAverage = ???????
PersonCount = ????????
WHEN NOT MATCHED THEN
INSERT(PersonId, PersonScore, PersonAverage, PersonCount)
VALUES(@PersonId, ????, ?????, ????)
.. and I'm not sure how I make sure the UPDATE
correctly only updates 1 row (ie... does that need a WHERE
clause?)
Finally, I based my this post on this SO question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

是的,这是可能的。不过你的语法不对。下面的似乎有效。我将 @PersonId 保留为表变量外部的单独标量变量,因为这就是您在问题中的使用方式。我假设 SomeTable 的主键是
PersonId
Yes it's possible. Your syntax was off though. The below seems to work. I have kept
@PersonId
as a separate scalar variable outside the table variable as that's how you have it in your question. And I have assumed that the Primary Key of SomeTable isPersonId