如何在 T-SQL 中编写简单的插入或更新?
我有一个流程,我不想跟踪某些内容是创建还是更新。跟踪会很复杂。我想执行创建或更新。该架构就像......
col1 varchar() (PK)
col2 varchar() (PK)
col3 varchar() (PK)
col4 varchar()
我正在考虑做什么,
TRY
{
INSERT ...
}
CATCH(DuplicateKeyException)
{
UPDATE ...
}
你有什么建议?
我想确保我理解其他投票最高的答案。给定我的模式,更新总是发生(即使使用插入),但插入仅发生在不存在的地方?
//UPSERT
INSERT INTO [table]
SELECT [col1] = @col1, [col2] = @col2, [col3] = @col3, [col4] = @col4
FROM [table]
WHERE NOT EXISTS (
-- race condition risk here?
SELECT 1
FROM [table]
WHERE [col1] = @col1
AND [col2] = @col2
AND [col3] = @col3
)
UPDATE [table]
SET [col4] = @col4
WHERE [col1] = @col1
AND [col2] = @col2
AND [col3] = @col3
I have a process that I do not want to track if something is a create or an update. Tracking would be complex. I would like to perform a create OR update. The schema is like...
col1 varchar() (PK)
col2 varchar() (PK)
col3 varchar() (PK)
col4 varchar()
I am thinking about doing
TRY
{
INSERT ...
}
CATCH(DuplicateKeyException)
{
UPDATE ...
}
What do you suggest?
I want to ensure that I understand the other top voted answer. Given my schema, the UPDATE always occurs (even with an INSERT), but the insert only occurs where it does not exist?
//UPSERT
INSERT INTO [table]
SELECT [col1] = @col1, [col2] = @col2, [col3] = @col3, [col4] = @col4
FROM [table]
WHERE NOT EXISTS (
-- race condition risk here?
SELECT 1
FROM [table]
WHERE [col1] = @col1
AND [col2] = @col2
AND [col3] = @col3
)
UPDATE [table]
SET [col4] = @col4
WHERE [col1] = @col1
AND [col2] = @col2
AND [col3] = @col3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这比先检查是否存在要快。
I think its quicker than checking existance first.
您可以使用 MERGE 语句(如果您使用的是 T-SQL )或构建一个查询,根据您的密钥是否存在执行 INSERT 或 UPDATE。
编辑:OP已编辑他的问题。是的,从技术上讲,每次执行此查询时,您都会运行 UPDATE 和 INSERT,但您只会使用这些语句之一来接触表,具体取决于满足哪个条件。
You can use the MERGE statement (if you're using T-SQL) or build a query that does an INSERT or UPDATE based upon the existence of your key.
Edit: OP has edited his question. Yes, you'll technically be running the UPDATE and INSERT every time this query is executed, but you'll only touch the table with one of those statements depending on which criteria is met.