在SQL Server 2008 SSMS中执行下面的语句:
create database test --创建数据库
go
use test
go
create table t_random(name nvarchar(10) not null,salary decimal(5,0) not null) --新建一个表
go
select * from t_random
go
insert into t_random values('zhangsan',1000), --插入数据
('lisi',2000),
('wangwu',5000)
go
select * from t_random
go
select name,salary,salary*round(RAND(),2) as comm from t_random --查询结果
go
输入结果:
name salary comm
zhangsan 1000 840
lisi 2000 1680
wangwu 5000 4200
这里面的round(rand(),2)是不是0.84,我如果想让他们随机数不一样呢?
select name,salary,salary*round(rand(checksum(newid())),2) as comm from t_random
结果如下:
name salary comm
zhangsan 1000 170
lisi 2000 1000
wangwu 5000 2600
再次执行select name,salary,salary*round(rand(checksum(newid())),2) as comm from t_random
name salary comm
zhangsan 1000 210
lisi 2000 480
wangwu 5000 2400
这个rand(checksum(newid()))在SQL Server中生成数据方面挺有用的。
当然我们还可以限制他的范围,比如我想让commn是salary的(0.8和1.2之间)乘积,可以使用salary*round(rand(checksum(newid()))*0.4+0.8,1)
在Oracle 10g中
create table t_random(name varchar2(10) not null,salary number);
select * from t_random;
insert into t_random values('zhangsan',1000);
insert into t_random values('lisi',2000);
insert into t_random values('wangwu',5000);
select * from t_random;
select name,salary,salary*round(dbms_random.value,2) as comm from t_random;
NAME SALARY COMM
zhangsan 1000 310
lisi 2000 260
wangwu 5000 2600
oracle中dbms_random这个包功能很强大的,这里只是涉及了一点。