如何在一个SQL语句(Oracle)中的两列中插入相同的随机值?

时间:2016-07-01 11:15:34

标签: sql oracle

我的例子不起作用:

INSERT INTO test_table 
 (column_1, column_2)
 VALUES (DBMS_CRYPTO.RANDOMBYTES(16), column_1); 

我对PL / SQL解决方案不感兴趣。

5 个答案:

答案 0 :(得分:3)

一种选择是使用标量子查询缓存:

INSERT INTO test_table (column_1, column_2)
SELECT random, random FROM
    (SELECT (SELECT dbms_crypto.randombytes(16) FROM dual) random FROM dual);

或使用PL / SQL:

DECLARE
    random RAW(16) := dbms_crypto.randombytes(16);
BEGIN
    INSERT INTO test_table (column_1, column_2) VALUES (random, random);
END;

答案 1 :(得分:1)

使用子查询:

INSERT INTO test_table(column_1, column_2)
  SELECT val, val
  FROM (SELECT DBMS_CRYPTO.RANDOMBYTES(16) as val FROM dual) x;

或者,这可以写成:

INSERT INTO test_table(column_1, column_2)
  WITH x AS (SELECT DBMS_CRYPTO.RANDOMBYTES(16) as val FROM dual)
  SELECT val, val
  FROM x;

答案 2 :(得分:1)

你可以创建一个临时表来存储它吗?

set echo on
create table test_table (column_1 varchar2(100), column_2 varchar2(100));

create global temporary table rando_val (c1 varchar2(100));

insert
into    rando_val
values  ( dbms_crypto.randombytes(16) );

INSERT INTO test_table (column_1, column_2)
select  c1,
        c1
from    rando_val;

commit;

select  *
from    test_table;

不是那么优雅,但它应该有用。

答案 3 :(得分:1)

尝试这个奇怪的查询

select /*+ NO_XML_QUERY_REWRITE  */  UTL_RAW.CAST_TO_RAW(VAL1),UTL_RAW.CAST_TO_RAW(VAL2) from 
       xmltable('for $c in . return <r><val1>{$c}</val1><val2>{$c}</val2></r>'
                  passing (SELECT UTL_RAW.CAST_TO_VARCHAR2(DBMS_CRYPTO.RANDOMBYTES(16)) as val FROM dual)
           columns
           "VAL1" varchar2(300) path '/r/val1',
            "VAL2" varchar2(300) path '/r/val2' )

如果您愿意,请不要在最后一步将varchar2再次转换为raw。这意味着

UTL_RAW.CAST_TO_RAW(VAL1)

答案 4 :(得分:0)

此解决方案适用于我:

INSERT INTO test_table(column_1, column_2)
  WITH x AS (SELECT /*+ MATERIALIZE */ DBMS_CRYPTO.RANDOMBYTES(16) as val FROM dual)
  SELECT val, val
  FROM x;

感谢Husqvik&amp;戈登林诺夫。