[英]Inserts and Updates in SQL Server for a stored procedure
I have a table like this in SQL Server: 我在SQL Server中有一个这样的表:
varID(PK) dataID(PK) is_used
A 1 0
B 1 0
Then I'm loading data to update is_used to 1 if the varID/dataID
combo exists and add it in otherwise. 然后,如果
varID/dataID
组合存在,则加载数据以将varID/dataID
更新为1,否则将其添加。
So I have to insert/update these varID/dataID
combos. 因此,我必须插入/更新这些
varID/dataID
组合。
varID(PK) dataID(PK)
B 1
C 1
So the updated table would look like this: 因此,更新后的表如下所示:
varID(PK) dataID(PK) is_used
A 1 0
B 1 1
C 1 1
What's the easiest way to do this? 最简单的方法是什么? I will do it in a stored procedure.
我将在存储过程中进行操作。
Procedure tries to update is_used
given a key. 过程尝试更新给定密钥的
is_used
。 If unsuccessful, inserts new row. 如果不成功,则插入新行。 Note I put 0 as default value for is_used - I think is_used = 1 for (C, 1) is an inadvertence.
注意,我将0作为is_used的默认值-我认为is_used = 1对于(C,1)是无意的。
create proc AddVarDataCombo (@varID varchar(100), @dataID int)
as
set nocount on
update ATable
set is_used = 1
where varID = @varID
and dataID = @dataID
if @@rowcount = 0
begin
insert into ATable
values (@varID, @dataID, 0)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.