如何在存储过程中不存在的插入?

时间:2015-11-06 02:05:05

标签: sql-server stored-procedures transactions not-exists

我正在创建一个存储过程来检查用户名是否存在,如果不存在则插入到用户表中,然后获取相同用户名的userid。这就是我的尝试

function unique(array){
    var tempObject = {};
    var returnArray = [];
    for (var i = 0; i < array.length; i++){
      if (!tempObject.hasOwnProperty(array[i])){
        tempObject[array[i]] = true;
        returnArray[i] = array[i];
      }
    }
    return returnArray;
  }
}

当我尝试执行它时说零行影响了..问题是什么?

alter Procedure Check_Name
    (--@idn integer,
     @username varchar(25),
     @password varchar(100)
     --@role_id integer)
As
Begin
    INSERT INTO [user] (username, [password]) 
        SELECT 
            username, [password]
        FROM 
            [user] AS u
        WHERE 
            NOT EXISTS(SELECT * FROM [user] AS t
                       WHERE u.username = t.username); 
End

1 个答案:

答案 0 :(得分:2)

也许你想要这样的事情:

Insert into user(username, password, role_id, date)
    Select @username, NULL, NULL, getdate()
    from user
    Where Not Exists(Select * from user where username = @username);  

但是,我建议在user(username)上添加一个唯一索引,然后使用try / catch块来捕获任何错误。我不认为需要单独的交易。