Passing parameter of C# DateTime to SQL Server 2005?
How do I pass C# DateTime
values (FromCreateDate
and ToCreateDate
) to SQL Server 2005 in order to select from a view ?
The result set CreateDate
column must be between FromDateDa开发者_如何学编程te
and ToCreateDate
.
Just set the parameter type to SqlDbType.DateTime
e.g
SqlCommand cmd = new SqlCommand("Select * From dbo.MyView Where createDate = @FromDate", SqlCon);
cmd.Parameters.Add(new SqlParameter(@FromDate, SqlDbType.DateTime));
cmd.Parameters["@FromDate"].Value = fromDate;
Exactly the same as you would any other parameter... of course it depends on how you are doing your data-access, but if we assume a SqlCommand
you'd just refer to a named parameter (@fromDate
/ @toDate
) in the TSQL, and add named SqlParameter
s (with .Value = theDate
) to the command:
DateTime end = DateTime.Today, start = end.AddDays(-7); // the last week
using (var conn = new SqlConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.Parameters.AddWithValue("@from", start); // fine for DateTime; for strings, use more explicit param
cmd.Parameters.AddWithValue("@to", end); // construction to avoid lots of different-length plans
cmd.CommandText = "SELECT COUNT(1) FROM [Users] WHERE LastSeen >= @from AND LastSeen < @to";
int count = (int) cmd.ExecuteScalar();
}
With LINQ etc you'd just use it in the query, i.e.
int count = db.Users.Count(user => user.LastSeen>=start && user.LastSeen<end);
I'm using a simple count in the examples just to keep it simple; obviously you can SELECT blah
from a VIEW
etc too...
精彩评论