易截截图软件、单文件、免安装、纯绿色、仅160KB

Sql NewId() 随机数 (转)


从A表随机取10条记录,用SELECT TOP 10 * from ywle order by newid()
order by 一般是根据某一字段排序,newid()的返回值 是uniqueidentifier ,order by newid()随机选取记录是如何进行的
newid()在扫描每条记录的时候都生成一个值, 而生成的值是随机的, 没有大小写顺序. 所以最终结果再按这个排序, 排序的结果当然就是无序的了
或者
select   top   10   *,newid()   as   Random   from   ywle where   ywlename='001'   ordey   by   Random
下者效率要高些
因为newid()返回的是uniqueidentifier类型的唯一值。newid()每次产生的值都不一样,那么根据这样的值进行排序,每次的结果也是不一样的。
原理是 把所有的ID出取然后用随机函数取出其中一个,然后用这个随机取到的ID去数据库里再取出记录,所有代价有点大。
sql server的随机函数newID()和RAND()
SELECT * from Northwind..Orders ORDER BY NEWID()
--随机排序
SELECT TOP 10 * from Northwind..Orders ORDER BY NEWID()
--从Orders表中随机取出10条记录
示例
A.对变量使用 NEWID 函数
以下示例使用 NEWID() 对声明为 uniqueidentifier 数据类型的变量赋值。在测试 uniqueidentifier 数据类型变量的值之前,先输出该值。
-- Creating a local variable with DECLARESET syntax.
DECLARE @myid uniqueidentifier
SET @myid = NEWID()
PRINT 'Value of @myid is '+ CONVERT(varchar(255), @myid)
下面是结果集:
Value of @myid is 6F9619FF-8B86-D011-B42D-00C04FC964FF
注意: 
NEWID 对每台计算机返回的值各不相同。所显示的数字仅起解释说明的作用。
随机函数:rand()
在查询分析器中执行:select rand(),可以看到结果会是类似于这样的随机小数:0.36361513486289558,像这样的小数在实际应用中用得不多,一般要取随机数都会取随机整数。那就看下面的两种随机取整数的方法:
1、
A:select  floor(rand()*N)  ---生成的数是这样的:12.0
B:select cast( floor(rand()*N) as int)  ---生成的数是这样的:12
2、
A:select ceiling(rand() * N)  ---生成的数是这样的:12.0
B:select cast(ceiling(rand() * N) as int)  ---生成的数是这样的:12
    其中里面的N是一个你指定的整数,如1


相关文档:

Rebuild indexes online with SQL Server 2005

Rebuild indexes online with SQL Server 2005
http://blogs.techrepublic.com.com/datacenter/?p=249
Online index rebuild
SQL Server 2005 introduces the ability to rebuild your indexes in an
online fashion so that other processes are able to access the table
while the rebuild is occurring. Because y ......

SQL生成随机字符串

declare @str varchar(50)
 declare   @i   int  
 set @str = ''
   set   @i=0  
   while   @i<50 
   begin  
        set   @str = ......

SQL面试题(转载)

SQL面试题(1)
create table testtable1
(
id int IDENTITY,
department varchar(12)
)
select * from testtable1
insert into testtable1 values('设计')
insert into testtable1 values('市场')
insert into testtable1 values('售后')
/*
结果
id department
1   设计
2   市场
3& ......

解决数据内有'的sql语句

SELECT OrderId, TableName, replace(PrimaryKeyColumn,'''','''''') as PrimaryKeyColumn, ColumnState,cast(IsUpdating as varchar) as IsUpdating, OperateTime, ValueColumn, SystemTypeID from SubCompFtpDataDairy where OperateTime>=dateadd(hh,-24,getdate()) ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号