The T-SQL generates random numbers of X non-repeating y-bit lengths

Source: Internet
Author: User
/* [Original] The T-SQL generates x random numbers of non-repeating y-bit lengths
By cuixiping (unintentional) 2007-04-13
(After testing, the speed is OK. It is also easy to change to a stored procedure, so I am too lazy to write .)

I can see an article by Dr. Yan:
How to quickly generate 1 million unique 8-bit numbers
Http://blog.csdn.net/zjcxc/archive/2006/08/20/1099215.aspx
I wrote it in another way.
*/
Declare @ x int;/* number of entries to be obtained */
Declare @ Y tinyint;/* The length to be obtained. The larger the value, the slower the value */
Declare @ I int;
Declare @ J bigint;
Declare @ sql1 varchar (1000 );
Declare @ sql2 varchar (1000 );
Declare @ sql3 nvarchar (2000 );
Set @ x = 100;
Set @ Y = 6;/* 10 @ Y must be greater than @ X. And @ Y should not be too large, otherwise it will be slow, and the number of machines is */
Set @ I = 2;
Set @ J = 10;

Use tempdb
-- create a test table and its data
If exists (select 1 from sysobjects where name = 'T' and type = 'U ')
drop table t;
Create Table T (N tinyint );
insert into T select 1
Union all select 2
Union all select 3
Union all select 4
Union all select 5
Union all select 6
Union all select 7
Union all Select 8
Union all select 9
Union all select 0
;
-- Assembly statement
set @ sql1 = 'select top' + Cast (@ X as varchar) + 't1.n * '+ Cast (Power (@ J, @ Y-1) as varchar);
set @ sql2 = 'as NN from t t1 ';
while @ I <= @ Y
begin
set @ sql1 = @ sql1 + '+ t' + Cast (@ I as varchar) + '. N * '+ Cast (Power (@ J, @ Y-@ I) as varchar);
set @ sql2 = @ sql2 + ', t t' + Cast (@ I as varchar);
set @ I = @ I + 1;
end
set @ sql3 = @ sql1 + @ sql2 + 'where t1.n> 0 order by newid ()';
-- execution statement
exec sp_executesql @ sql3;
-- delete test
drop table t;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.