September 2009
S M T W T F S
« Aug   Dec »
 12345
6789101112
13141516171819
20212223242526
27282930  

T-SQL Random Number Generator [with NEWID()]

One interesting thing about T-SQL (the flavor or SQL that comes with Microsoft SQL Server), is that the RAND() function to seed a random number is called once per query. You can work around this using user defined functions, OR, just use the NEWID() function.

NEWID creates a GUID, but can be cast into a whole manner of different data types. I like this:

DECLARE @maxval TINYINT, @minval TINYINT
select @maxval=24,@minval=5

update tbl_orders set quantity=CAST(((@maxval + 1) - @minval) *
    RAND(CHECKSUM(NEWID())) + @minval AS TINYINT)
    where abs(quantity)>24
Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • HackerNews
  • LinkedIn
  • Reddit
  • Slashdot

1 comment to T-SQL Random Number Generator [with NEWID()]

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>