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

标签 sql-server stored-procedures merge sql-server-2000 upsert

我想检查表PREMIUM_SERVICE_USER是否存在任何记录
如果没有strClientID记录插入timeValid表,则strClientIDpremium_service_user更新为+30。

我究竟做错了什么?

它会增加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

最佳答案

您的问题是运行第一个if而不考虑@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, timeReg, timeValid, bCurrent, durum) VALUES (@strClientID,getdate(),getdate() + 30,'1','1')
        UPDATE TB_USER SET cash = cash+200 WHERE strAccountID = @strClientID
       END
  end

关于sql-server - 检查记录是否存在,如果是,则“更新”,如果不是,则“插入”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3189293/

相关文章:

sql-server - 配置 Access 报表以使用 SQL Server 存储过程作为其记录源

sql-server - SQL Server 存储过程中的文本搜索

android - 如何从两种不同的方法插入数据库

sql - Oracle 中看似关键的保留 View 的更新引发 ORA-01779

git - Msys Git merge 工具命令选项问题

.net - 使用 PowerShell 从 SQL Server 中获取整行

sql - 在 MS SQL Server 中使用 truecrypt

stored-procedures - SSRS : Passing different parameter values to stored procedure for two Data Sets

mysql - 仅向用户提供 GRANT EXECUTE 'procedure'(无选择或插入权限)

svn - 颠覆: more files than expected when merging a branch to trunk