<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: prng code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sat, 26 Jul 2008 12:07:09 GMT</pubDate>
    <description>DZone Snippets: prng code</description>
    <item>
      <title>PRNG In SQL Select </title>
      <link>http://snippets.dzone.com/posts/show/4033</link>
      <description>Simple example of a PRNG (pseudo-random number generator) written into a SQL statement&lt;br /&gt;&lt;br /&gt;Example is in T-SQL, but it ports well&lt;br /&gt;&lt;br /&gt;Actual application should use either a better random algorithm, or the output be used with randomized seeds. This is definitely not cryptographically secure. It's very handy if you need a simple random number with your recordset though.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;-- Setup some vars we'll need&lt;br /&gt;DECLARE @prng TABLE (seed BIGINT, rnum nchar(10))&lt;br /&gt;DECLARE @seeds TABLE (seed BIGINT)&lt;br /&gt;DECLARE @seed BIGINT&lt;br /&gt;DECLARE @C1 BIGINT, @C2 BIGINT, @C3 BIGINT&lt;br /&gt;SET @seed = 0&lt;br /&gt;SET @C1 = 1664525&lt;br /&gt;SET @C2 = 4294967296&lt;br /&gt;SET @C3 = 1013904223&lt;br /&gt;&lt;br /&gt;-- Create a seed table so we can have some data to use&lt;br /&gt;WHILE @seed &lt; 10&lt;br /&gt;BEGIN&lt;br /&gt;    INSERT INTO @seeds (seed) VALUES (@seed)&lt;br /&gt;    SET @seed = @seed + 1&lt;br /&gt;END&lt;br /&gt;&lt;br /&gt;-- Create our PRNG (inserts into table for illustrative purposes)&lt;br /&gt;-- prng(seed) ::= ((((C1 * seed) % C2) + C3) % C2) / C2&lt;br /&gt;-- Then convert prng(seed) into a string&lt;br /&gt;-- of 10 chars, 8 of which are decimal places&lt;br /&gt;INSERT INTO @prng&lt;br /&gt;SELECT&lt;br /&gt;    seed,&lt;br /&gt;    REPLACE(&lt;br /&gt;        STR(&lt;br /&gt;            ( CAST((((@C1*seed)%@C2)+@C3)%@C2 AS FLOAT) )&lt;br /&gt;            / ( CAST(@C2 AS FLOAT)),&lt;br /&gt;            10, 8&lt;br /&gt;        ),&lt;br /&gt;        ' ', '0') AS rnum&lt;br /&gt;FROM @seeds&lt;br /&gt;&lt;br /&gt;-- Let's take a look at what we created&lt;br /&gt;SELECT * FROM @prng&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 17 May 2007 00:39:32 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4033</guid>
      <author>jokeyxero (xero)</author>
    </item>
  </channel>
</rss>
