Npgsql版本3.2.5
我正在尝试为ADO.NET/npgsql编写sql生成器。唯一感兴趣的功能是相关实体的单个/批量插入,可以为任何插入返回自动生成的值。
方案
CREATE TABLE tbl
(
id bigserial not null PRIMARY KEY,
data integer not null
);
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;
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
。