Modify SQL for a schema datatable at runtime

Is there a way I can modify the SQL of a schema datatable at runtime?

Basically I’ve got a read-only datatable defined which uses manually-created SQL which includes parameters.
This works fine but I need to modify this SQL slightly at runtime in some cases to make some changes to the where clause beyond the scope of what’s possible with dynamic where.

The changes wouldn’t alter any of the existing parameters or fields, I just need to modify the SQL slightly before it executes.

How can I best achieve this?

Actually I’ll elaborate because there’s far more to it than that.

I have a read-only datatable with manually-created SQL as I said. This will be opened by the client to fetch the data from the server.

Now, there are a great many conditions that I need to incorporate into the WHERE clause of this datatable’s SQL. Most of them I’ve managed to accomodate via parameters, which is great, but there are some where I can’t do this.

Basically I need to incorporate an EXISTS subquery into the WHERE clause of the datatable to check whether data exists in other tables. The problem is that the subquery inside the EXISTS will itself need a where clause with an arbitrary number of conditions.

So basically I’ll have this type of SQL:

SELECT Field1,Field2,…
FROM Table
WHERE Condition1
AND Condition2
AND EXISTS (SELECT 1 FROM SubTable WHERE SubTable.ParentId = Table.Id AND SubCondition1 AND SubCondition2…)

Basically the number of sub-conditions in the subquery will be arbitrary depending on criteria entered by the user.

Whilst I can manually code the EXISTS into the datatable’s SQL, I can’t have an arbitrary number of conditions on it so I need to somehow do this at runtime.

I need the client to be able to open a parameterised datatable as normal, but somehow forward additional criteria to the server which it can then use to add the EXISTS clause onto the end of the SQL before it runs.

Can you suggest how I could achieve this?

have you tried to join SubTables and then use usual dynamic where conditions ?

Possibly. I’m experimenting with using XML parameters at the moment