Passing C # DateTime parameter to SQL Server 2005?

How to pass a value of C # DateTime( FromCreateDateand ToCreateDate) in SQL Server 2005 for the selection of the presentation?

The end column CreateDatemust be between FromDateDateand ToCreateDate.

+5
source share
2 answers

Just like any other parameter ... Of course, it depends on how you make your data access, but if we accept SqlCommand, you just refer to the named parameter ( @fromDate/ @toDate) in TSQL and add the command SqlParameter(c .Value = theDate) to 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 will just use it in the request, i.e.

int count = db.Users.Count(user => user.LastSeen>=start && user.LastSeen<end);

, ; , SELECT blah VIEW .. ...

+5

SqlDbType.DateTime

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;
+8

All Articles