我在“IF”附近遇到语法错误,并带有以下查询:
myDataBase.execSQL("IF EXISTS (SELECT * FROM ANSWERS WHERE QUESTION_ID=" + id +" AND PLAYER ='" + player + "')" +
"UPDATE ANSWERS SET "+field+"=1"
+ " WHERE QUESTION_ID=" + id + " AND LEVEL =" + level +" AND PLAYER='" + player + "' ELSE "
+ "INSERT INTO ANSWERS (level, player, question_id, "+field+") VALUES (level, player, id, 1)");
不知道我哪里出错了..有人看到了吗?
near "IF": syntax error: IF EXISTS (SELECT * FROM ANSWERS WHERE QUESTION_ID=6 AND PLAYER ='nob')UPDATE ANSWERS SET showhint1=1 WHERE QUESTION_ID=6 AND LEVEL =1 AND PLAYER='nob' ELSE INSERT INTO ANSWERS (level, player, question_id, showhint1) VALUES (level, player, id, 1)
答案 0 :(得分:1)
请参阅this question的答案:
select exists(
select * from answers ...
);
答案 1 :(得分:1)
编辑:我喜欢这条评论的原始答案:sackoverflow.com/questions/418898 / ... - zapl 7分钟前。我不知道你能做到这一点。它的效率非常高......
我做得很快。希望你能得到这个想法...所以这些变量和东西将在非sql代码中。我建议使用存储过程或类似的东西,如果你可以....或完全分离所有部分(看它是否存在,基于这个sql,或如果它不做这个sql)。
仅使用更新语句....如果表中不存在变量,则不会更新任何内容。并且只使用insert语句...如果表中存在变量,则不会插入任何内容。除了这两个陈述之外,不需要做出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 )
答案 2 :(得分:0)
If exists
不是在SQL更新语句中使用的有效关键字。