Random Number SKU Generator

From: "Peter Dabrowski" <meritage(at)mail(dot)com>
To: pgsql-novice(at)postgresql(dot)org
Subject: Random Number SKU Generator
Date: 2015-02-13 09:46:06
Message-ID: trinity-b2dae1a6-807e-42bc-bf5f-ee782c9221ea-1423820766030@3capp-mailcom-lxa08
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

<html><head></head><body><div style="font-family: Verdana;font-size: 12.0px;"><div>I use a Luhn algorithm to generete random number, inserted below sql code to column &#39;SKU&quot;</div>

<div>&nbsp;</div>

<div>ALTER TABLE m_product ALTER sku SET DEFAULT ltrim(to_char(luhn_generate(round(random()*10000)::int), &#39;00000&#39;))</div>

<div>&nbsp;</div>

<div>as a result on record saving random number is generated, but my problem is the numbers are not unique.</div>

<div>&nbsp;</div>

<div><font color="#000000">Somone sugest that I&nbsp; should write a function to en<font face="arial, sans-serif" size="2">capsulate &quot;ltrim(to_char(luhn_generate(</font></font>

<div><font color="#000000" face="arial, sans-serif" size="2">round(random()*10000)::int), &#39;00000&#39;))&quot; &nbsp;and at the same time, check if the value is already used in the table.</font></div>

<div>&nbsp;</div>

<div><font color="#000000" face="arial, sans-serif" size="2">in pseudo code it would look something like this:</font></div>

<div>&nbsp;</div>

<div>generateMProductSKU(){<br/>
&nbsp;&nbsp;&nbsp; skuGen=&quot;&quot;<br/>
&nbsp;&nbsp;&nbsp; needToGenerate = true<br/>
&nbsp;&nbsp;&nbsp; while(needToGenerate){<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; skuGen = ltrim(to_char(luhn_generate(round(random()*10000)::int), &#39;00000&#39;))<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if((Select count(*) from M_Product where sku =skuGen) = 0<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; needToGenerate =&nbsp; false<br/>
&nbsp;&nbsp; }<br/>
&nbsp;&nbsp; return skuGen<br/>
}</div>

<div>&nbsp;</div>

<div>Culd somebody help me tu structure code into right sql format so it could be inserted into database.</div>

<div>&nbsp;</div>

<div>Thank you very much.</div>

<div>Peter</div>
</div></div></body></html>

Attachment Content-Type Size
unknown_filename text/html 1.8 KB

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Roxanne Reid-Bennett 2015-02-13 15:20:45 Re: Random Number SKU Generator
Previous Message Chuck Roberts 2015-02-11 11:55:15 How to create tables and copy records in blocks?