SQL-创建长度为5的随机varchar

时间:2015-06-26 18:43:30

标签: sql database db2

我需要使用SQL创建varchar(5)值。字符串只能包含字母和数字,不能包含特殊字符。我试过这个(见下文),但这不起作用。

CHAR(ROUND(RAND() * 93 + 30, 0));

任何有关正在发生的事情的想法都会受到赞赏。完整代码如下所列。

merge into fundtype as fund using (select fundtypnum, fundtype, country from table(values 
('JRLH5','$FOCA$01$$','USA'),
('YLHOV','$FOCA$02$$','AUS'),
('0MGJA','$FOCA$02$$','USA'),
('UK235','$FOCA$03$$','CAN'),
('HJP3C','$FOCA$03$$','USA')
))
as newfund (fundtypnum,fund_type,country) 
on (
 (fund.fund_type = newfund.fund_type and fund.country = newfund.country) or
 (fund.fundtypnum = newfund.fundtypnum)
)
when not matched then 
 insert (fundtypnum,fund_type,country) values (
    CHAR(ROUND(RAND() * 93 + 30, 0)),
    newfund.fund_type,
 newfund.country);

2 个答案:

答案 0 :(得分:1)

将CHAR(ROUND(RAND()* 93 + 30,0)更改为

CONCAT(substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',CEIL(RAND()*36),1),
    substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',CEIL(RAND()*36),1),
    substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',CEIL(RAND()*36),1),
    substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',CEIL(RAND()*36),1),
    substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',CEIL(RAND()*36),1))

答案 1 :(得分:0)

扩展Dan Bracuk的评论......尝试这样的事情:

SELECT substring(reverse(sys.fn_varbintohexstr(CONVERT(varBINARY(8),
ABS(Checksum(NewID()) % 1000000)))),1,5)