在手动运行脚本时,脚本无法在ADO.NET中执行

时间:2017-12-19 16:41:12

标签: c# sql postgresql ado.net npgsql

上下文

Npgsql版本3.2.5

我正在尝试为ADO.NET/npgsql编写sql生成器。唯一感兴趣的功能是相关实体的单个/批量插入,可以为任何插入返回自动生成的值。

实施例

上下文

方案

CREATE TABLE tbl
(
    id bigserial not null PRIMARY KEY,
    data integer not null
);

在pgAdmin

中手动运行的脚本
start transaction isolation level READ COMMITTED;

with t as (
    insert into tbl ( data) values ( '1' )
    returning id, data
) select id, data into temporary firstInsert from t;

with t as (
    insert into tbl ( data )
    select data + '1' as data from firstInsert
    returning id
) select id into temporary secondInsert from t;

select id from secondInsert;

-- commit;

C#go

string tableName = "tbl";
string columnName = "data";
string autogenColumnName = "id";
string script = $@"
with t as (
    insert into {tableName} ( {columnName} ) values ( '1' )
    returning {autogenColumnName}, {columnName}
) select {autogenColumnName}, {columnName} into temporary firstInsert from t;

with t as (
    insert into {tableName} ( {columnName} )
    select {columnName} + '1' as {columnName} from firstInsert
    returning {autogenColumnName}
) select {autogenColumnName} into temporary secondInsert from t;

select {autogenColumnName} from secondInsert;";

using ( NpgsqlConnection conn = new NpgsqlConnection( Executor.Executor.ConnectionString ) )
{
    conn.Open();
    using ( NpgsqlTransaction transaction = conn.BeginTransaction( System.Data.IsolationLevel.ReadCommitted ) )
    using ( NpgsqlCommand comm = new NpgsqlCommand( script, conn, transaction ) )
    using ( NpgsqlDataReader reader = comm.ExecuteReader() )
    {
        reader.Read();
        reader.GetInt64( 0 );
        reader.Read();
        reader.Close();
        transaction.Commit();
    }
}

问题

在pgAdmin上运行一切正常,但在{#1}} c#中调用Npgsql.PostgresException : 42P01: relation "firstinsert" does not exist

0 个答案:

没有答案