仅在第一次计数时更新

时间:2018-07-26 17:24:01

标签: sql sql-server

仅当计数为1时计数器才会计数,随后的加法则不会计数

if exists (select 1 from login_counter where emailaddress = @useremail)
    update login_counter 
    set counts = counts+1, - here i want to add a check if the count is 1, add the lasttry which is justbelow to the date but every new count, don't update that 
        lasttry = GETDATE() 
    where emailaddress = @useremail;
else
    insert into login_counter (counts, emailaddress, lasttry) 
    values (1, @useremail, GETDATE());

我这样尝试过:

仅当计数为1时计数器才会计数,随后的加法则不会计数

if exists (select 1 from login_counter where emailaddress = @useremail)
    update login_counter 
    set counts = counts + 1,
        lasttry = CASE WHEN (select lasttry from login_counter where emailaddress = @useremail) = NULL THEN GetDate() 
    where emailaddress = @useremail;
else
    insert into login_counter (counts,emailaddress,lasttry) 
    values (1, @useremail, GETDATE());

我收到此错误:

  

第156条消息,级别15,状态1,第5行
  关键字“ where”附近的语法不正确

2 个答案:

答案 0 :(得分:0)

我不明白您要做什么,但是由于以下行,您遇到语法错误:

lasttry = CASE WHEN (select lasttry from login_counter where emailaddress = @useremail) = NULL THEN GetDate()

缺少END表达式的CASE

答案 1 :(得分:0)

我认为您可能可以像这样重写案例声明:

lasttry = CASE WHEN NOT EXISTS (select lasttry from login_counter where emailaddress = @useremail) THEN GetDate() END

否则,您将要确保CASE中的子查询仅返回单个值,例如SELECT TOP 1 lasttry ...SELECT MAX(lasttry) ...。如果子查询返回多个值,则比较表达式将炸弹。