1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CodeIgniterでDBのsequenceを取得すると2・3個ずつ値が進んでしまう時の対応

Posted at

現象

CodeIgniterで、シーケンスの値を取得するためnextvalを発行すると、取得する値が増分の設定値を超えて増えてしまう。

oracleのシーケンスでnextvalの値取得
$sql = 'SELECT test_seq.nextval AS NEXTVAL FROM dual';

$query = $this->db->query($sql);

$row = $query->row_array();
echo "nextval: ".$row['NEXTVAL']."<br>";

シーケンスを増分1設定で上のコードを2回実行したとき、結果が下のように値が2増加してしまっている。。。

2回実行した結果

nextval: 1
nextval: 3

フォーラムでも取り上げられているが、
http://forum.codeigniter.com/thread-17356-page-2.html
CodeIgniterで値を取得すると、2・3回アクセスされているようです。(それパフォーマンス的に良くないのでは?)

解決策

simple_queryで値を取得せずに、"NEXTVAL"を実行して値を1つ進めた後"CURRVAL"で値を取得する。

シーケンス取得

public function get_new_id($seq_name)
{
    $sql = 'SELECT ' . $seq_name . '.NEXTVAL FROM DUAL'; // シーケンスを進める
    $this->db->simple_query($sql);//値を取得しない

    $sql = 'SELECT ' . $seq_name . '.CURRVAL FROM DUAL'; // シーケンスの取得
    $query = $this->db->query($sql);
    $row = $query->row_array();

    return $row['CURRVAL'];
}

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?