sql-server – 检查是否存在记录,如果是“更新”,如果不是“插入”

前端之家收集整理的这篇文章主要介绍了sql-server – 检查是否存在记录,如果是“更新”,如果不是“插入”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果有任何记录,我想检查表PREMIUM_SERVICE_USER
strClientID update timeValid为30,如果没有strClientID的记录插入到premium_service_user表中.

我究竟做错了什么?

它将timeValid增加30天,但也插入另一行.

SELECT @pre_var = count(*) 
FROM PREMIUM_SERVICE_USER 
WHERE strClientID = @strClientID

/* bronze premium - 200 cash */
IF @Premium = 1
BEGIN
    INSERT INTO PREMIUM_SERVICE_USER 
        (strClientID,timeReg,timeValid,bCurrent,durum) 
    VALUES 
        (@strClientID,getdate(),getdate() + 30,'1','1')

    UPDATE TB_USER 
    SET cash = cash+200 
    WHERE strAccountID = @strClientID
END

IF @Premium = 1 AND @pre_var = 1
BEGIN
    UPDATE PREMIUM_SERVICE_USER 
        SET timevalid = timevalid+30 where strClientID = @strClientID
    UPDATE PREMIUM_SERVICE_USER 
        SET bCurrent = 1 where strClientID = @strClientID
    UPDATE TB_USER 
        SET cash = cash+200 WHERE strAccountID = @strClientID
END

解决方法

如果不考虑@pre_var的值,您的问题是运行第一个.

这是一个稍微不同的方式,如果PREMIUM_SERVICE_USER很大,这将略微更有效.

if @Premium = 1
  begin
    if exists(Select 1 From PREMIUM_SERVICE_USER Where strClientID = @strClientID)
      BEGIN
        update PREMIUM_SERVICE_USER set timevalid = timevalid+30 where strClientID = @strClientID
        update PREMIUM_SERVICE_USER set bCurrent = 1 where strClientID = @strClientID
        UPDATE TB_USER SET cash = cash+200 WHERE strAccountID = @strClientID
       END
    ELSE
      BEGIN
        INSERT INTO PREMIUM_SERVICE_USER (strClientID,durum) VALUES (@strClientID,'1')
        UPDATE TB_USER SET cash = cash+200 WHERE strAccountID = @strClientID
       END
  end
原文链接:https://www.f2er.com/mssql/82529.html

猜你在找的MsSQL相关文章