Sqlserver批量生成10w不重复8位数字
项目中需要批量生成100W不重复的8位数,百度了一大把,修改成了如下Sql,做下笔记,希望对看到的朋友有帮助(下面是生成10W条,条数自己改,性能还可以)
表名:makeExtensionCode
字段:extension_code, is_used, createTime,具体跟句自己需求改动
CREATE PROCEDURE makeExtensionCode AS DECLARE
@dt datetime
SET @dt = GETDATE()
SET NOCOUNT OFF DECLARE
@row INT
SET @row = 100000 --记录总数为10W
WHILE @row > 0
BEGIN
RAISERROR ('need %d rows', 10, 1, @row) WITH NOWAIT
SET ROWCOUNT @row INSERT weixin_extension_code SELECT
extension_code = RIGHT (
100000 + CONVERT (
bigint,
ABS(CHECKSUM(NEWID()))
),
8
),
is_used = 0,
createTime = GETDATE()
FROM
syscolumns c1,
sysobjects o
SET @row = @row - @@ROWCOUNT --设置下次循环需要插入的记录数量
--删除重复数据
DELETE odao_mobile.dbo.weixin_extension_code
WHERE
extension_code IN (
SELECT
extension_code
FROM
odao_mobile.dbo.weixin_extension_code
GROUP BY
extension_code
HAVING
COUNT (extension_code) > 1
)
AND extension_code_id NOT IN (
SELECT
MIN (extension_code_id)
FROM
odao_mobile.dbo.weixin_extension_code
GROUP BY
extension_code
HAVING
COUNT (extension_code) > 1
)
END
GO