今天去面试了一家公司,有一个题目比较有趣

本文介绍了一种使用SQL生成1万个不重复的由26个小写字母组成的唯一编号的方法。通过联合多个选择语句并利用临时表,实现了编号的生成与插入。另外还提供了一个利用newid()函数结合字符串处理来生成唯一编号的替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/* 
题目
 
如何产生1万个编号,插入到表 T(col varchar(20))中,并且不能重复,编号只能从26个小写字母中取 . 
*/ 
 
--1.当时的写法 
select  'a'  as col 
into    #t 
union  
select  'b'  union 
select  'c'  union 
select  'd'  union 
select  'e'  union 
select  'f'  union 
select  'g'  union 
select  'h'  union 
select  'i'  union 
select  'j'  union 
select  'k'  union 
select  'l'  union 
select  'm'  union 
select  'n'  union 
select  'o'  union 
select  'p'  union 
select  'q'  union 
select  'r'  union 
select  's'  union 
select  't'  union 
select  'u'  union 
select  'v'  union 
select  'w'  union 
select  'x'  union 
select  'y'  union 
select  'z'   
 
 
 
 
insert  into T 
select    top 10000  a.col+b.col+c.col       from  #t  a,#t b ,#t c 
  
drop  table #t  
 
 
  
 
 

-------------------------------------------------------------- 
  
--2.看到varchar(20), 想到newid(),再做一些字符串处理 
 
insert  into T 
select top  10000 
         replace( replace( replace( replace( replace( replace( replace( replace( replace( replace(lower( left( replace(newid(), 
                                                              '-', ''),  20)), 
                                                              ' 0', 'a'),  1
                                                              'b'),  2, 'c'),  3
                                                              'd'),  4, 'e'),  5
                                                'f'),  6, 'g'),  7, 'h'),  8, 'i'), 
                 9, 'j')  as col 
from    sys.all_columns , 
        sys.all_objects 
         
 
 
  
  
         
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值