views:

860

answers:

3

Hi, I’m using C# and Winforms. I’m trying to make a report that gives a list of people that need to renew their memberships if they expire within a user supplied date range. I've got a connection to an Access file, and I'm trying to set up a fill query for a TableAdapter, and I can’t figure out how to put a variable in my "WHERE" clause. The below SQL works to do what I need but obviously I don’t want to hard code the dates. I would like to substitute the dates with the variables “fromDate” and “toDate”. How can I do this? Thanks.

SELECT   [Last Name], [First Name], [Renewal Date]
FROM     Members
WHERE    ([Renewal Date] >= #1/1/2000#) AND ([Renewal Date] <= #1/1/2012#)
ORDER BY [Renewal Date]
+3  A: 

In access here you can find how to define in a query that a value will be used as a paramater.

Here you can find samples of how to set parameter values in .net.

jvanderh
That's good info jvanderh, But I'm looking for how to modify the SQL inside a TableAdapter. So all I really need is the SQL. Thanks.
JimDel
@JimDel - jvanderth is totaly right. You should use the parametrized query in tableadapter and you should changed values in parameters.
TcKs
@JimDel: you do _not_ want to modify the SQL. Use a parameterized query, and set the parameters.
John Saunders
I'm just a beginner and am having trouble finding a tutorial on how to do this.
JimDel
Did you read the two links above, in my answer?
jvanderh
I suppose it does jvanderh, I'm just having trouble implementing it. I guess I just need to do some more research around the topic. But thanks for getting me started.
JimDel
+1  A: 

I don't use TableAdapters, so I could be wrong in this, but you could try doing the following:

DateTime startDate = ...somedate;
DateTime endDate = ...somedate;
myTableAdapter.SelectCommand.Text = GetExpiringMembershipsSql(startDate, EndDate);

...

public static void GetExpiringMembershipsSql(DateTime startDate, DateTime endDate)
{
    string template = @"SELECT   [Last Name], [First Name], [Renewal Date]
FROM     Members
WHERE    ([Renewal Date] >= #{0}#) AND ([Renewal Date] <= #{1}#)
ORDER BY [Renewal Date]";

    return string.Format(template, startDate.ToShortDateString(), endDate.ToShortDateString());
}

This is a rather dirty approach and utilizing parameters would be better, but I'm not very familiar with how access handles parameters.

Aethyrial
+1  A: 

I did a similar thing this morning in a Typed Dataset. I wanted the tableadapter of the typed dataset to get only certain rows. If you open the Typed Dataset in the designer, right-click on it, and choose Configure... you can adjust the Select query. Add a "Where" part, and include your parameter like this:

select * from shoes where shoecolor = @ColorParameter

In code when you are using the tableadapter to fill the dataset, you'll be able to add the value to use for the parameter there.

Jon