From: Jamey Cribbs Date: 2005-11-13T13:36:01+09:00 Subject: Re: KirbyBase 2.3: How to insert record if key does not exist basi wrote: >Hello, > >I have a word frequency table, thus: > >tgl_tokens = db.create_table( >:tgltokens, >:tgltoken, :String, >:count, :Integer) > >With data from a hash, I'm trying to insert a record into the table, >but only if the key does not exist in the table. If it does, then add >the new frequency count into the stored frequency count. > > tgl_texts.select.each do |t| > freq = Hash.new(0) > for word in t.text.to_s.downcase.tr_s('^A-Za-z-',' ').split(' ') > freq[word] += 1 > end > freq.delete("") > > freq.each do |w,c| > -- if w exists in tgl_tokens, then > -- add c to the stored count value of w > -- else > tgl_tokens.insert do |token| > token.tgltoken = w > token.count = c > end > -- end > end >end > >Basically the KirbyBase / Ruby syntax that eludes me corresponds to >this SQL snippet: > >begin > select 1 into v_dummy > from tgltokens > where tgltoken = w; >-- if found then > update tgltokens > set count = count + c > where tgltoken = w; >exception > when no_data_found then > insert into tgltokens values (w, c); >end > > If I understand you correctly, you would simply do this: freq.each do |w,c| if tgl_tokens.select { |token| token.tgltoken == w }.size > 0 tgl_tokens.update { |token| token.tgltoken == w }.set do |token| token.count += c end else tgl_tokens.insert do |token| token.tgltoken = w token.count = c end end end Jamey Cribbs