views:

204

answers:

2

Hey,

I want to convert the following SQL Query to a SubSonic Query.

SELECT [dbo].[tbl_Agency].[ParentCompanyID] FROM [dbo].[tbl_Agency] WHERE REPLACE(PhoneNumber, ' ', '') LIKE REPLACE('%9481 1111%', ' ', '')

I thought I would do it like below, but I just can't get it to produce valid SQL.

     //SubSonic
     string agencyPhoneNumber = "9481 1111";
     SubSonic.SqlQuery subQueryagencyPhoneNumber = new SubSonic.Select(Agency.ParentCompanyIDColumn.ColumnName);
            subQueryagencyPhoneNumber.From(Agency.Schema.TableName);

     //WHERE
     subQueryagencyPhoneNumber.Where("REPLACE(" + Agency.PhoneNumberColumn.ColumnName + ", ' ', '')").Like("%" + agencyPhoneNumber + "%");

Does anyone out there know how to fix this - I'm using SubSonic 2.2. I feel like I'm taking crazy pills here - this should be straightforward, right?

Cheers, JohnBob

+1  A: 

I think you'll need to add the like expression to the inline SQL.
Something like:

var whereSql = string.Format("REPLACE({0}, ' ', '') Like '%{1}%'", Agency.PhoneNumberColumn.ColumnName, agencyPhoneNumber);

subQueryagencyPhoneNumber.Where(whereSql);

See a similar question at http://stackoverflow.com/questions/697593/calling-an-sql-function-from-a-subsonic-select

Matt Lacey
Thanks for the comment, but this didn't work.It doesn't register the above statement as a valid constraint.
JohnBob
Gave up and did it as a stored procedure with dynamic sql.blazergh! Wanted to do it in SubSonic, ah well.
JohnBob
@JohnBob Could always do it as a CodingHorror to keep all the logic in code
Matt Lacey
+1  A: 

If worst comes to worst with really complicated queries you can still use subsonic using the .CodingHorror() methods as described @ http://subsonicproject.com/docs/CodingHorror

As long as you select valid column names that subsonic knows about when you cast the collection -> .ExecuteAsCollection() you'll be fine and still be able to use you Active record.

This has saved me a lot of times when i've had really large complicated queries. Just make sure you still use the parameters and clean your statements so that your input is sanitized.

Doug