编辑: 我喜欢对原始答案的评论:sackoverflow.com/questions/418898/… – zapl 7 分钟前。我不知道你能做到这一点。看起来很高效....
我很快就做到了。希望你明白了......所以这些变量和东西将在非 sql 代码中。如果可以的话,我建议使用存储过程或类似的东西....或完全分离所有部分(查看它是否存在,基于执行此 sql,或者是否不执行此 sql)。
仅使用更新语句....如果表中不存在变量,则不会更新任何内容。并且仅使用插入语句...如果表中确实存在变量,则不会插入任何内容。除了这两个语句之外,不需要 if 或任何东西来实际检查答案中是否存在某些东西。
create table #answers (question_id int, player int, level int, other_field int)
insert into #answers values (1,1,1,1)
insert into #answers values (2,1,1,1)
declare @question_id int
declare @player int
declare @level int
declare @other_field int
set @question_id=1
set @player=1
set @level=1
set @other_field=1
-- if it exists already
update a
set other_field=@other_field
from #answers as a
where QUESTION_ID=@question_id and
PLAYER=@player and
other_field<>@other_field
set @question_id=4
set @player=4
set @level=1
set @other_field=1
-- if it doesn't exist
insert into #answers (question_id, player, level, other_field)
select x.QUESTION_ID, x.player, @level, @other_field
from #answers a
right outer join
(select @question_id as QUESTION_ID,
@player as player) as x
on x.QUESTION_ID=a.QUESTION_ID and
x.player=a.player
where a.player is null and a.question_id is null
或者如果它不存在(更混乱但更短)
-- if it doesn't exist
insert into #answers (question_id, player, level, other_field)
select distinct @QUESTION_ID, @player, @level, @other_field
from #answers
where not exists (select 1 from #answers where
QUESTION_ID=@question_id and
PLAYER=@player )