I'm porting an app from firebird to postgres and there is a bunch of nested sql commands. The first command is necessary for the second one to run, there are some functions that have 5 or 6 nested commands and they are all using the same connection. I just wanted to know if there is a way to do all this on one connection without having to rewrite the whole thing.
static void NestedCommandsOnOneConnection()
{
using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
{
using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM tableA", connection))
{
using (NpgsqlDataReader reader = command.ExecuteReader())
{
using (NpgsqlCommand command2 = new NpgsqlCommand("SELECT * FROM tableB where column1 = @column1", connection))
{
command2.Parameters.AddWithValue("@column1", reader["column1"]);
using (NpgsqlDataReader reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
//Do things
}
}
}
}
}
}
}
//Edit: Would it be better if i do something like this?
static void NestedCommandsOnOneConnection()
{
using (NpgsqlConnection connection = new NpgsqlConnection(ConnectionString))
{
var column1 = "";
using (NpgsqlCommand command = new NpgsqlCommand("SELECT * FROM tableA LIMIT 1", connection))
{
using (NpgsqlDataReader reader = command.ExecuteReader())
{
while(reader.Read())
{
column1 = reader["column1"].ToString();
}
}
}
using (NpgsqlCommand command2 = new NpgsqlCommand("SELECT * FROM tableB where column1 = @column1", connection))
{
command2.Parameters.AddWithValue("@column1", column1);
using (NpgsqlDataReader reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
//Do things
}
}
}
}
}
When the second command gets executed I get the error msg "a command is already in progress: SELECT * FROM tableA" So is there any way to do this without having to make a connection for each command?
SELECT * from TableB where column1 in (SELECT column1 from TableA). Performance will probably be multiple times better than the slow client-side loop