首页 > 解决方案 > oracle执行动态sql选择脚本并返回表格数据

问题描述

我正在尝试执行动态 sql 选择语句并将结果返回给 C# ExecuteReader。

我可以使用以下 sql 代码在 sql server 中检索结果。

Create Table TestCustomer(ID Varchar(50), CustomerName Varchar(100));

Insert Into TestCustomer (ID, CustomerName) Values ('1', 'One');
Insert Into TestCustomer (ID, CustomerName) Values ('2', 'Two');
Insert Into TestCustomer (ID, CustomerName) Values ('3', 'Three');

DECLARE @SQLScript VARCHAR(MAX), @CustomerName VARCHAR(100);

SET @CustomerName = 'Two';
SET @SQLScript = 'select * from TestCustomer where CustomerName = '''+ @CustomerName +''' ';
EXEC(@SQLScript);

在此处输入图像描述

但是当我尝试使用以下 oracle sql 代码在 oracle 服务器上检索结果时,我没有看到表结果像 sql server 那样出现。

DECLARE 
SQLScript VARCHAR2(4000);
CustomerName VARCHAR2(20) := 'Two';
BEGIN
SQLScript := 'select * from TestCustomer where CustomerName = :CustomerName';
EXECUTE IMMEDIATE SQLScript USING CustomerName;
END;

在此处输入图像描述

动态sql脚本执行后如何返回表格结果,以便c#获取表格结果?

标签: oracleoracle-sqldeveloper

解决方案


在 Oracle 中,您必须将结果返回到某些东西中。例如,进入一个局部变量,如本例所示:

样品表:

SQL> create table testcustomer as
  2    select 1 id, 'One' customername from dual union all
  3    select 2   , 'Two'              from dual;

Table created.

PL/SQL 块:

SQL> set serveroutput on
SQL> declare
  2    sqlscript      varchar2(4000);
  3    l_customername testcustomer.customername%type := 'Two';
  4    retval         testcustomer.id%type;
  5  begin
  6    sqlscript := 'select id from testcustomer ' ||
  7                 'where customername = :1';
  8    execute immediate sqlscript into retval using l_customername;
  9
 10    -- retval now contains the ID returned by that SELECT statement
 11    dbms_output.put_line('ID = ' || retval);
 12  end;
 13  /
ID = 2

PL/SQL procedure successfully completed.

SQL>

但是,如果您想实际返回该值以便它可以在其他地方使用,请考虑使用function。稍作调整,代码如下:

SQL> create or replace function f_test
  2    (par_customername in testcustomer.customername%type)
  3    return testcustomer.id%type
  4  is
  5    sqlscript      varchar2(4000);
  6    retval         testcustomer.id%type;
  7  begin
  8    sqlscript := 'select id from testcustomer ' ||
  9                 'where customername = :1';
 10    execute immediate sqlscript into retval using par_customername;
 11
 12    -- retval now contains the ID returned by that SELECT statement
 13    return retval;
 14  end;
 15  /

Function created.

SQL> select f_test('One') from dual;

F_TEST('ONE')
-------------
            1

SQL>

当然,你可以返回各种东西;我返回了一个标量值。您可以返回一个 refcursor、一个数组……这取决于您需要什么。

看看有没有帮助。


推荐阅读