如何在SQL Server中获取数字随机uniqueid [英] How to get numeric random uniqueid in SQL Server

查看:323
本文介绍了如何在SQL Server中获取数字随机uniqueid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQL Server 2005,请告诉我如何为表中的每一行获取6位数字(唯一数字,应为随机数).

I am using SQL Server 2005, please tell me how can I get 6 digits (unique numeric which should be random) value for every row in table.

我在表中有一个字段,我需要6位数字值(随机且唯一).

I have a field in table in which I need 6 digit numeric value (random and unique).

请帮助我做到这一点.

推荐答案

SELECT ABS(CHECKSUM(NEWID())) % 999999

获取电话号码:

SELECT RIGHT('000000' + CAST(ABS(CHECKSUM(NEWID())) % 999999 AS varchar(6)), 6)

NEWID与您在SQL Server中获得的随机性差不多.

NEWID is about as random as you can get in SQL Server.

但是,如果要唯一,则最好从000000开始,然后转到999999.任何随机生成器都将命中

However, if you want unique, you may as well start at 000000 and go to 999999. Any random generator will hit the birthday problem.

您可以拥有可靠的唯一身份或随机身份,但不能同时拥有这两者

You can have unique or random that are reliable, but not both reliably

这篇关于如何在SQL Server中获取数字随机uniqueid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆