Using SQL Server Date datatype and C# DateTime to select records - sql

I have an ActionResult where I want to select records based on a date column in SQL Server. This date is in a column of type Date. I can't directly compare the dates since C# DateTime includes the time component and the Date datatype does not. Is there a nice way to do this?
public ActionResult AbsencesByDate(DateTime date)
{
var absences = from attendance in db.Attendances
where attendance.Date == date
select new
{
returnedPersonID = attendance.PersonID,
FullName = attendance.Person.FName + " " + attendance.Person.LName,
};
return Json(absences, JsonRequestBehavior.AllowGet);
}

You could remove the time part from your date parameter in your function.
Something like this :
public ActionResult AbsencesByDate(DateTime date)
{
date = date.Date;
var absences = from attendance in db.Attendances
where attendance.Date == date
select new
{
returnedPersonID = attendance.PersonID,
FullName = attendance.Person.FName + " " + attendance.Person.LName,
};
return Json(absences, JsonRequestBehavior.AllowGet);
}

try using:
where attendance.Date == date.Date

Related

Dapper for NET Core: Insert into a table and return id of inserted row [duplicate]

This question already has answers here:
How do I perform an insert and return inserted identity with Dapper?
(9 answers)
Closed 6 months ago.
I have the following method in my repository. As of now, i believe the int returned is simply one indicating whether or not the operation was successful. I want the int to be the id (which is the single column of the table) to be returned after a successful execution. How do i accomplish this?
public async Task<int> AddNewGroup()
{
using(_connection)
{
_connection.Open();
var id = await _connection.ExecuteAsync("INSERT INTO groups").Single();
}
}
You can run a query which has 2 parts, first is your INSERT part and second is a SELECT part. In the SELECT part, you can return(select) whatever column value you want.
For example, If your group table has a primary key column called GroupId and you have set that column for Identity value generation(automatic value generation), you can call the SCOPE_IDENTITY() to get the generated value.
We will use the QueryAsync method.
public async Task<int> AddNewGroup()
{
using(_connection)
{
_connection.Open();
var q = #"INSERT INTO Groups(Name,Description) VALUES
(#name, #desc); SELECT CAST(SCOPE_IDENTITY() as int)"
var result = await _connection.QueryAsync<int>(q,
new { #name="some name", #desc="some desc"});
return result.Single();
}
}
You don't have to create by hand the insert query, you can use Dapper.Contrib github which helps you to manage CRUD operations.
Using Dapper.Contrib you can do something like:
public async Task<int> AddNewGroup(Group entity)
{
using (_connection)
{
_connection.Open();
var id = await _connection.InsertAsync(entity);
}
}
If you're using SQL Azure / SQL Server, you need to return the inserted value from the query using something like
INSERT INTO groups OUTPUT inserted.id VALUES (...)
and then instead using ExecuteAsync use ExecuteScalarAsync
Reference to the OUTPUT clause here:
https://learn.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql?view=sql-server-2017
public static void Main()
{
string sql = #"INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
Values (#CustomerName, #ContactName, #Address, #City, #PostalCode, #Country);
SELECT CustomerID FROM Customers WHERE CustomerID = SCOPE_IDENTITY();";
using (var connection = new SqlConnection(GetConnectionString()))
{
Customer c = new Customer("Brian Adams", "Brian", "12 Jones Place", "New York", "NY12", "CA");
var id = connection.QueryFirstOrDefault<int>(sql, c);
Console.WriteLine("The Customer ID is " + id);
sql = "Select * FROM CUSTOMERS WHERE CustomerID = #ID";
var rc = connection.QueryFirstOrDefault<Customer>(sql, new{ #ID = id });
}
}
}
The "correct" way that I took is (Showing repository method using Guid Id to return):
public async Task<Guid> CreateClient(ClientEntity clientModel)
{
const string sql = #"
INSERT INTO dbo.Clients
(
ClientCode,
Name,
IsActive
)
OUTPUT Inserted.ClientId
VALUES
(
#ClientCode,
#Name,
#IsActive
)";
using var dbConnection = await _databaseProvider.GetConnection();
var result = await dbConnection.ExecuteScalarAsync(sql, new
{
ClientCode = clientModel.Code,
Name = clientModel.Name,
IsActive = clientModel.IsActive
});
if (result != null)
{
return Guid.Parse(result.ToString());
}
else {
return Guid.Empty;
}
}
You can use the RETURNING id in the insert statement. This is using C# and dapper.
private readonly NpgsqlConnection _connection = new NpgsqlConnection();
var sqlInsert = $""""
INSERT INTO tabel_name (column_name)
VALUES ('value')
RETURNING id;
"""";
var id = await _connection.ExecuteScalarAsync(sqlInsert);
And if you want to determine the key type coming back you can use:
var id = await _connection.ExecuteScalarAsync<int>(sqlInsert);
Where you specify the type in the <> brackets. If you do not specify, it will return the object type.

ResultSet getDate(1)

How to return oracle.sql.DATE from ResultSet?
It returns a Java date, not the ORACLE date.
I get an error:
Type mismatch: cannot convert from Date to DATE
ResultSetIterator iter;
...
ResultSet rs = iter.getResultSet();
if (rs.next()) {
date = rs.getDate(1);
}
My query:
SELECT MIN(date_created) FROM tbl_user group by date_created;
What is oracle.sql.DATE? Do you mean java.sql.Date?
What do you mean by java Date? Do you know that java.sql.Date is subclass of java.util.Date?
try this what will be the output?
ResultSet rs = iter.getResultSet();
if (rs.next()) {
date = rs.getDate(1);
if (date instanceof java.sql.Date)
System.out.println("sql date");
if (date instanceof java.util.Date)
System.out.println("util date");
}
edit:
I see here you can probably do something like this:
ResultSet rs = iter.getResultSet();
if (rs.next()) {
date = rs.getDate(1);
if (date instanceof java.sql.Date)
return new oracle.sql.DATE(date);
}
You can cast the ResultSet to an OracleResultSet and then use the getDATE() method:
OracleResultSet rs = (OracleResultSet)iter.getResultSet();
if (rs.next()) {
oracle.sql.DATE date = rs.getDATE(1);
}

How to convert this sql part to linq

select sum(DATEDIFF(day,LeaveBreakup.StartDate,LeaveBreakup.EndDate)+1)
what I want is to convert the statement to linq select statement
class LeaveBreakup
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
List<LeaveBreakup> Dates = new List<LeaveBreakup>();
Dates.Add(new LeaveBreakup(){StartDate = DateTime.Now.AddDays(-3), EndDate = DateTime.Now });
Dates.Add(new LeaveBreakup(){StartDate = DateTime.Now.AddDays(-2), EndDate = DateTime.Now });
LINQ BIT
var Result = (from D in Dates
select (D.EndDate - D.StartDate).TotalDays + 1)
.Sum();
If you want to know the diff without having to worry about having a negative value then wrap the calculation in Math.Abs
var Result = (from D in Dates
select Math.Abs((D.StartDate - D.EndDate).TotalDays) + 1)
.Sum();
In this example your Result is 7

asp.net mvc , raw sql : Display data in Views generated using aggregate function

I am using ASP.NET MVC, EF 6 and SQL Server 2008.
I want to generate a view which would show sum of all the sales in each day for a particular month in a particular year.
I found LINQ query very complicated in such type of job, So I used a raw SQL query. I wrote query and tested in SQL server and it worked fine.
select
YEAR(Date) as Year,
MONTH(Date) as month,
DAY(Date) as date,
SUM(GrandTotal) as Total
from
Sales
where
Year(Date) = 2014
and MONTH(Date) = 12
group by
DAY(Date), YEAR(Date), MONTH(date)
Result
Well currently I don't have much data. But it looks like I got what I wanted from a query.
I wrote a controller for this purpose and now I have no idea how to display this data in View.
public ActionResult MonthlySalesByDate()
{
DateTime today = DateTime.Now.Date;
int _year = today.Year;
int _month = today.Month;
//raw sql query
string query = "select SUM(GrandTotal) as Total, DAY(Date) as date, MONTH(Date) as month, YEAR(Date) as Year from Sales where Year(Date) = " + _year + " and MONTH(Date) =" + _month + " Group by DAY(Date), YEAR(Date), MONTH(date)";
//executing raw sql query
var _model = db.Stocks.SqlQuery(query).ToList();
return View(_model);
}
Please help me out with this. If there is better way of doing this or if I am making mistakes, please let me know.
Start by creating view models to represent what you want to display in the view
public class DayTotalVM
{
public int Day { get; set; }
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Total { get; set; }
}
public class SalesVM
{
[DisplayFormat(DataFormatString = "{0:MMMM yyyy}")]
public DateTime Date { get; set; }
public List<DayTotalVM> Days { get; set; }
}
The sql query you have can be generated in linq and projected into your view models using
int year = 2014;
int month = 12;
var query = db.Sales.Where(x => x.Date.Year == year && x.Date.Month == month)
.GroupBy(x => x.Date).Select(g => new DayTotalVM
{
Day = g.Key.Day,
Total = g.Sum(x => x.Total)
})
However this will only give you the 2 items as per you above image, but from the comments you want to display all days in the month, so you can add
int daysInMonth = DateTime.DaysInMonth(year, month);
List<DayTotalVM> days = new List<DayTotalVM>();
for(int i = 1; i < daysInMonth + 1; i++)
{
DayTotalVM item = new DayTotalVM () { Day = i };
DayTotalVM ex = query.Where(x => x.Day == i).FirstOrDefault();
if (ex != null)
{
item.Total = ex.Total;
}
days.Add(item);
}
and finally initialize and return your view model
SalesVM model = new SalesVM();
{
Date = new DateTime(year, month, 1),
Days = days
}
return View(model);
And then the view would be
#model SalesVM
#Html.DisplayFor(m => m.Date);
<table>
#for(int i = 0; i < Model.Days.Count; i++)
{
<tr>
<td>#Html.DisplayFor(m => m.Days[i].Day)</td>
<td>#Html.DisplayFor(m => m.Days[i].Total)</td>
</tr>
}
</table>
Edit
The for loop could be replace by using a GroupJoin()
public ActionResult MonthlySalesByDate(int year, int month)
{
int daysInMonth = DateTime.DaysInMonth(year, month);
var days = Enumerable.Range(1, daysInMonth);
var query = db.Sales.Where(x => x.Date.Year == year && x.Date.Month == month).Select(g => new
{
Day = g.Date.Day,
Total = g.Total
});
var model = new SalesVM
{
Date = new DateTime(year, month, 1),
Days = days.GroupJoin(query, d => d, q => q.Day, (d, q) => new DayTotalVM
{
Day = d,
Total = q.Sum(x => x.Total)
}).ToList()
};
return View(model);
}

Querying SQLite in android( Summation of column values)

Hi guys I want to get the summation of column values from my sqlite database in android.
and am trying to use this to get me the sum of column KEY_COST.
public Cursor fetchAllCost() {
return mDb.query(
DATABASE_TABLE,
new String[] { "SUM(KEY_COST)"},
null,
null,
null,
null,
null);
}
but its giving me a cursor and I do not know how to get the value from the Cursor object. Any one help!!!
You can return scalar values like so:
public int getColumnData() {
mDb = mDbManager.getReadableDatabase();
final SQLiteStatement stmt = mDb
.compileStatement("SELECT SUM(KEY_COST) FROM...");
// Cast as appropriate
return (int) stmt.simpleQueryForLong();
}
Or alternatively, depending on the data type use simpleQueryForString().
You should just move to the first result in the cursor with cursor.moveFirst() and then you can do cursor.getInt(1) to get the scalar value.
rawQuery
Sum value is on first column - cursor.getInt(0);
Cursor cursor = database.rawQuery(
"SELECT SUM(" + COL_NAME + ") FROM " + TABLE_NAME, null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
query
String[] columns = new String[] {
"sum(" + DbHelper.C_COUNT_OF_WORDS + ")"
};
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
String limit = null;
database = dbHelper.getReadableDatabase();
Cursor cursor = database.query(DbHelper.TABLE_STATISTICS, columns, where, whereArgs, groupBy, having, order, limit);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}