对于需要一次更新或插入所有值的情况,不仅仅是一条记录,我使用了这个片段
第一次运行更新脚本
更新表1
设置 OPIS = T1.OPIS
从
表 1 AS T
内部联接
表2 AS T1
在
T.col = T1.col;
然后执行插入脚本
插入表 1
选择 * 从
(
选择 T1.* 表 2 作为 T1
LEFT JOIN Table1 AS T2 ON (T2.col = T1.col)
T2.col 为空
) 作为 T;
希望有人发现这很有用。
MySql 中的 this 等价物(在某些情况下)是这样的:
插入表 (a,b,c) 值 (1,2,3)
重复密钥更新 c=c+1;
有人可以发现这与SQL Server 上的 INSERT OR UPDATE 解决方案中的文章有关
使用MERGE (Transact-SQL) 的更新版本:
DECLARE @USER_ID AS INT=76;
DECLARE @TYPE AS NVARCHAR(MAX)='set.global';
DECLARE @FKEY AS NVARCHAR(MAX)='21';
DECLARE @DATA AS NVARCHAR(MAX)='test';
begin tran
MERGE UserData
USING (SELECT @USER_ID, @TYPE, @FKEY, @DATA) AS Source([UserId], [Type], [FKey], [Data])
ON (UserData.[UserId] = Source.[UserId] AND UserData.[Type] = Source.[Type] AND (UserData.[FKey] = Source.[FKey] OR (Source.[FKey] IS NULL AND UserData.[FKey] IS NULL)))
WHEN MATCHED
THEN
UPDATE SET [Data] = Source.[Data]
WHEN NOT MATCHED BY TARGET THEN
INSERT
([UserId]
,[Type]
,[FKey]
,[Data])
VALUES
( Source.[UserId]
,Source.[Type]
,Source.[FKey]
,Source.[Data]);
commit tran