Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Random Values and Dates

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2008-02-24 : 21:00:21
Hello,

I am creating some dummy data in a table using the following Numbers Table:

declare @Numbers table
(
n int identity(1,1) not null primary key clustered
)
while coalesce(scope_identity(), 0) <= 4
begin
insert @Numbers default values
end

And for inserting data in a table I am doing something like:

insert into dbo.Categories (CategoryID, [Name])
select
newid(),
'Category ' + right('000' + convert(varchar(3), n + 1), 3)
from @Numbers

However I need to insert also a few random values and dates.

This is where I am having the problem. I get always the same values.

What I need and I am using is:

1. A random date inside the range of -30 to +30 days of current date

DATEADD(day, Round(((@UpperDay - @LowerDay - 1) * Rand() + @LowerDay), 1), getdate())

2. A random date inside the range of -60 to -30 days of current date

DATEADD(day, Round(((@LowerDay -1) * Rand() + @LowerDay), 1), getdate())

3. A random date inside the range of +30 to +60 days of current date

DATEADD(day, Round(((@UpperDay - 1) * Rand()), 1), getdate())

4. A random date inside the range of -40 years to 0 years of the current date

DATEADD(year, Round(((@LowerYear -1) * Rand() + @LowerYear), 1), getdate())

5. A random float with 1 decimal between 0 and 4

Round(((@UpperRating - @LowerRating - 1) * Rand() + @LowerRating), 1)

6. A random int number between 0 and 5

Round(((@UpperWeight - @LowerWeight -1) * Rand() + @LowerWeight), 0)

7. A random bit

convert(int, 2*rand())

What am I doing wrong?

Thanks,
Miguel

nathans
Aged Yak Warrior

938 Posts

Posted - 2008-02-24 : 23:52:59
The rand() function will eval only once per query. You will need to use newid() which evals once per row.

Get with Jeff: http://weblogs.sqlteam.com/jeffs/archive/2004/11/22/2927.aspx




Nathan Skerl
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2008-02-25 : 10:22:42
The functions on the following links might be helpful. They will generate ranmon integers and datetimes.

Random Integer, Sample, and Datetime Functions
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=69499

CODO ERGO SUM
Go to Top of Page

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2008-02-25 : 12:11:18
I am following these articles to insert dummy data in the database, random numbers, random dates, etc:

http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html

http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html

What do you think?

Thanks,
Miguel
Go to Top of Page
   

- Advertisement -