0

我通过以下查询在“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)
4

3 回答 3

1

请参阅此问题的答案:

select exists(
    select * from answers ...
);
于 2012-11-16T18:56:24.933 回答
1

编辑: 我喜欢对原始答案的评论: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 )
于 2012-11-16T19:53:44.247 回答
0

If exists不是在 SQL 更新语句中使用的有效关键字。

于 2012-11-16T19:23:52.950 回答