Changing the SQL Server JOIN "ON" clause

Posts   
 
    
derrick
User
Posts: 40
Joined: 14-Jan-2004
# Posted on: 21-Dec-2005 19:57:10   

is there any way that I can add predicate expressions to the "ON" clause for a table JOIN in SQL Server?

Currently I have a typed list that issues a SQL statement something like this

SELECT * FROM table1 LEFT JOIN table2 ON table1.ID = table2.table1ID

What I would like to do is add an expression to the ON clause like this

SELECT * FROM table1 LEFT JOIN table2 ON table1.ID = table2.table1ID AND table2.expire_date > getdate()

Can I do this with a custom EntityRelation?

bclubb
User
Posts: 934
Joined: 12-Feb-2004
# Posted on: 22-Dec-2005 02:48:17   

You can set a CustomFilter in the relation.

Custom filters for EntityRelations The JOIN clauses themselves are determined from the relation objects, thus FK-PK compares which result in the ON clause. Sometimes it is important to specify additional predicates in this ON clause. You can do this by specifying an IPredicateExpression instance for the CustomFilter property of the EntityRelation you add to a RelationCollection. In the example below we add a custom predicate to the EntityRelation object of the relation Customer-Order and which filters on Order.ShipCountry="Mexico". It uses the example of Multi-entity filters.

// C#
IPredicateExpression customFilter = new PredicateExpression();
customFilter.Add(PredicateFactory.CompareValue(OrderFieldIndex.ShipCountry, ComparisonOperator.Equal, "Mexico"));
// ... 
bucket.Relations.Add(CustomerEntity.Relations.OrderEntityUsingCustomerID).CustomFilter = customFilter;
// ...

' VB.NET
Dim customFilter As IPredicateExpression = New PredicateExpression()
customFilter.Add(PredicateFactory.CompareValue(OrderFieldIndex.ShipCountry, ComparisonOperator.Equal, "Mexico"))
' ... 
bucket.Relations.Add(CustomerEntity.Relations.OrderEntityUsingCustomerID).CustomFilter = customFilter
' ...

Please pay special attention to the flag EntityRelation.CustomFilterReplacesOnClause. If this flag is set to true, it will make the join construction logic to use a specified CustomFilter as the ON clause instead of appending it with AND to the field relation clause.