如何在数据库中使用默认值随机字符串创建列


Answers:


11

PostgreSQL示例:

CREATE OR REPLACE FUNCTION f_random_text(
    length integer
)
RETURNS text AS
$body$
WITH chars AS (
    SELECT unnest(string_to_array('A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9', ' ')) AS _char
),
charlist AS
(
    SELECT _char FROM chars ORDER BY random() LIMIT $1
)
SELECT string_agg(_char, '')
FROM charlist
;
$body$
LANGUAGE sql;


DROP TABLE IF EXISTS tmp_test;


CREATE TEMPORARY TABLE tmp_test (
    id serial,
    data text default f_random_text(12)
);


INSERT INTO tmp_test
VALUES 
    (DEFAULT, DEFAULT),
    (DEFAULT, DEFAULT)
;


SELECT * FROM tmp_test;

 id |     data
----+--------------
  1 | RYMUJH4E0NIQ
  2 | 7U4029BOKAEJ
(2 rows)

显然,您可以执行此操作。(当然,您也可以添加其他字符,或者也可以使用其他随机字符串生成器,例如this。)


1
选择md5(random():: text); -就是这样,谢谢!
tasmaniski 2012年

17

解决方案是(对于PGSQL):

alter TABLE users ADD column register_key text NOT NULL default md5(random()::text);

1
这是一个美丽的把戏!
cjauvin
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.