简体   繁体   English

如何通过PL / SQL中的变量动态插入?

[英]How to insert dynamically through a variable in PL/SQL?

Lets create a table first 让我们先创建一个表

create table test
(
  id number,
  name varchar2(20)
);

Now during insert, I want to hold the data into variable first & then dynamically pass the variable into the VALUES clause like this: 现在在插入过程中,我想先将数据保存到变量中,然后将变量动态传递给VALUES子句,如下所示:

declare
  v_data varchar2(50);
begin
  v_data:='1,sunny';
  execute immediate 'insert into test values(v_data)';
  commit;
end;

But its showing some errors(Not enough values)...... plz help how to achieve this?? 但是它显示出一些错误(没有足够的值)……请帮助实现这一目标?

Table test has two columns. 表测试有两列。 You're only inserting one and not naming which column it is hence "not enough values". 您只插入一个,而不是命名哪个列,因此“值不足”。 So you need: 因此,您需要:

INSERT INTO test (name) VALUES (data)

or probably better is to put in an ID: 或者最好输入一个ID:

INSERT INTO test (id, name) VALUES (1, data)

or simply: 或者简单地:

INSERT INTO test VALUES (1, data)

For this kind of thing though I would use a cursor rather than dynamic SQL (or even inline SQL). 对于这种事情,尽管我会使用游标而不是动态SQL(甚至是内联SQL)。

You need to use different variables for each value 您需要为每个值使用不同的变量

declare 
  v_data1 number
  v_data2 varchar2(50);
begin 
  v_data1 :=1
  v_data2 = 'sunny'; 

  insert into test values(v_data1,v_data2);
  -- Alternatively insert into test (Name) values (v_data2);
commit; 
end;

The normal way to pass values into dynamic SQL statements is with bind variables like this: 将值传递到动态SQL语句中的常规方法是使用绑定变量,如下所示:

declare 
   v_id integer;
   v_name varchar2(50);
begin
   v_id := 1;
   v_name := 'sunny';
   execute immediate
      'insert into test (id, name) values(:b1, :b2)'
      using v_id, v_name; 
   commit; 
end;

That needs one variable per value. 每个值需要一个变量。

Your approach works, but you need to adjust your query a little: 您的方法可行,但您需要稍微调整一下查询:

execute immediate 'insert into test values(' || v_data|| ')';

so that the contents of your v_data variable are actually inserted into the string, not the value "v_data" itself. 以便将v_data变量的内容实际插入字符串中,而不是值“ v_data”本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM