I want to return Distinct records from a table in SQLITE flutter by giving some condition such as return All the distinct records where ID = x (where x will be taken by the user).
How can I achieve this?
Working with the SQFlite package you can use a query or a rawQuery to perform that, in both cases you need to pass the where arguments as an array, and for the distinct operator you can do it as follows:
/// [GET] Get all the data by date using a query
getData(String date) async {
final db = await database;
final response = await db.query(
"TableExample",
distinct: true,
orderBy: 'id',
where: 'date = ?',
whereArgs: [date],
);
//...
}
/// [GET] Get all the data by date using a rawQuery
getDailyPollResponsesPerRangeDate(String date) async {
final db = await database;
final response = await db.rawQuery(
"SELECT DISTINCT TableExample.id, TableExample.date "
"FROM TableExample "
"WHERE TableExample.date == ? "
"ORDER BY TableExample.date DESC",
[date],
);
//...
}
Related
LINQ to Entities does not recognize the System.String ToString(System.String) method, and this method cannot be translated into a store expression.
List<ModelName> List = await (
linq query write here
select new ModelName
{
Column Name,
chkIN = VD.CheckIN.ToString(),
}).ToListAsync();
List<ModelName> List = await (
linq query write here
select new ModelName
{
Column Names,
checkin = VD.CheckIN.Value
}).ToListAsync();
List.ForEach(x => x.chkIN = x.checkin.HasValue ? DateTime.Today.Add(x.checkin.Value).ToString("hh:mm tt") : "");
return List;
I need to update one field only in my table :
static Future<void> updateType(Statement statement, String type) async {
await db.update('StatementTABLE',
{'type' : '?'},
where: "id = ?",
whereArgs: [type,statement.id]);
}
But I have this error message :
"DatabaseException(Too many bind arguments. 3 arguments were provided
but the statement needs 2 arguments.) sql 'UPDATE StatementTABLE SET
type = ? WHERE id = ?' args [?, Sortie,
56fcb6b0-a283-11eb-a4d4-1ffc954983be]}"
I do not understand as I have well 2 arguments and not 3 ..
whereArgs is only to replace values in whee clause. type should be in the map :
await db.update('StatementTABLE',
{'type' : type},
where: "id = ?",
whereArgs: [statement.id]);
A simple setup: department: employee, 1:M and a search form that filters on FirstName =, lastname =, email contains, age >=, join date <= and related department = .
A submit button will then open up a results page with the datasource set to the appropriate search method. I have direct filtering where we bind to #datasource,query.filters.FirstName_equals, etc. I have a datasource based on a query buillder solution and a third solution based on a query script. A appropriate search results page opens on Submit and the datasource of the results page is set to the appropriate datasource: filter, query builder or query script.
The solution that uses a query script and a results page based on this datasource is as follows:-
query script
var params = query.parameters;
return getEmployeeRecords_(
params.param_FirstName,
params.param_LastName,
params.param_Email,
params.param_StartDate,
params.param_Age,
params.param_Department
);
and
function getEmployeeRecords_( firstName, lastName, email, startDate, age,
department) {
var ds = app.models.Employee.newQuery();
if ( firstName )
ds.filters.FirstName._equals = firstName;
if ( lastName )
ds.filters.LastName._equals = lastName;
if ( email )
ds.filters.Email._contains = email;
if ( startDate )
ds.filters.StartDate._greaterThanOrEquals = startDate;
if ( age )
ds.filters.Age._lessThanOrEquals = parseInt(age, 10);
if ( department )
ds.filters.Department.Department._equals = department;
var records = ds.run();
var recs = records.length;
// update calculated model with record count
var calculatedModelRecords = [];
var calculatedModelRecord = app.models.Employee_RecordCount.newRecord();
calculatedModelRecord.RecordCount = recs;
calculatedModelRecords.push(calculatedModelRecord);
return records;
}
On the results page for the query script datasource paging is just broken. A query that correctly returns 8 records where the query page size is set to 5 allows me to get the pager to go to page 1000 if I wished, but the datasource always stays on the first page of records. With page size set to e.g., 100 the correct result set is clearly displayed. The direct binding and query builder datasources work as expected.
The reason for doing these different searches is as a test and evaluate each option, and also to be able to return a record count, which I can only do with a query script.
Anyone any ideas as to the cause of this aberrant App Maker behaviour ?
Also when I query the calculated model Employee_RecordCount to retrieve the record count using a UI label with text of "Number of Records: " + #datasources.Employee_RecordCount.item.RecordCount this shows null.
What's the best way to retrieve the record count using the calculated model Employee_RecordCount?
I'm not sure if your actual code omits the {} with each if statement or if you just didn't include them in your question. However, see my proposed changes to your code below:
function getEmployeeRecords_( firstName, lastName, email, startDate, age, department) {
var ds = app.models.Employee.newQuery();
if ( firstName !== null ) {
ds.filters.FirstName._equals = firstName;
}
if ( lastName !== null ) {
ds.filters.LastName._equals = lastName;
}
if ( email !== null) {
ds.filters.Email._contains = email;
}
if ( startDate !== null) {
ds.filters.StartDate._greaterThanOrEquals = startDate;
}
if ( age !== null) {
ds.filters.Age._lessThanOrEquals = parseInt(age, 10);
}
if ( department !== null) {
ds.filters.Department.Department._equals = department;
}
var records = ds.run();
var recs = records.length;
// update calculated model with record count
var calculatedModelRecord = app.models.Employee_RecordCount.newRecord();
calculatedModelRecord.RecordCount = recs;
return [calculatedModelRecord];
}
As for the paging issue, for some reason AM has always had that problem with calculated models. There may be a bug report filed in their AM issue tracker.
These are my model classes
I have three tables
But when I update my model, the PurchaseReturnDetail table is not there in the model, and it creates a one-to-many relationship between PurchaseReturn and PurchaseDetail.
I'm using repository pattern and I don't know how to insert transactions in PurchaseReturnDetail table.
Following is my code to insert transaction. but it gives exception
Message = "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."
public async Task<Response> SaveAsync(PurchaseReturn purchaseReturn, List<string> serialNoList)
{
PurchaseReturnRepository rep = new PurchaseReturnRepository();
decimal totalRate = 0;
foreach (var serialNo in serialNoList)
{
var purchaseDetail = await PurchaseService.Instance.GetSinglePurchasedItemDetailAsync(serialNo);
purchaseReturn.PurchaseDetails.Add(purchaseDetail);
//Calculating total rate to update supplier balance
totalRate += purchaseDetail.Rate;
}
var response = await rep.AddAsync(purchaseReturn);
if (response.Success)
{
//Updating Supplier Balance
response = await SupplierService.Instance.UpdataBalanceAsync(purchaseReturn.SupplierId, totalRate, false);
response.Msg = "Items has beed returned and stock is updated";
}
return response;
}
NOTE : I'm using database first approach
I have ASP.NET application and we use Dapper library. The code that produces the error looks as following:
public bool CheckIfExists(IEnumerable<long> ticketGroups, long dateId, int userId)
{
bool bRetVal = false;
string sql = "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)";
using (var conn = CreateSqlConnection())
try
{
int rows = conn.Execute(sql, ticketGroups.Select(g => new { SubTypeId = g, UserId = userId, dateId }));
if (rows > 0)
bRetVal = true;
}
catch (SqlException ex)
{
throw new Exception("Error", ex);
}
return bRetVal;
}
When I run the application it throws the exeption: Incorrect syntax near ')'
As you can see, there can be more tickets (IEnumerable type) with the same date and user.
I'm not sure what's going on.
That is because it is not valid SQL to start with an if (If you mean to use T-SQL it is, but then you have to write the entire if statement)
I think a simple case is what you need:
select case
when exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)
then 1
else 0
end
Your query "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)" return some data if the table have some so for that it require something to work on. Like if else condition in programming we can modify this as :
if exists
(select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)
Print 'Have Data'
else
Print 'Don't Have data'
Rewriting your code :
public bool CheckIfExists(IEnumerable<long> ticketGroups, long dateId, int userId)
{
bool bRetVal = false;
string sql = "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId) Print '**your code to execute if exist data**' else Print '**your code to execute if doesnot exist data**'";
using (var conn = CreateSqlConnection())
try
{
int rows = conn.Execute(sql, ticketGroups.Select(g => new { SubTypeId = g, UserId = userId, DateId = dateId }));
if (rows > 0)
bRetVal = true;
}
catch (SqlException ex)
{
throw new Exception("Error", ex);
}
return bRetVal;
}
this link will help you more :
https://dba.stackexchange.com/questions/30159/exist-select-from-my-table
If your result depends on the number of rows and not on what's returned from the SQL, you could try this:
if exists ([whatever]) select 1
This works, because if there are no matching values, no recordset is returned, and your affected record count is zero.
You could also try something a bit simpler:
select 1
from T_TicketGroupsToChangePrice
where SubTypeId = #SubTypeId
and DateId = #dateId
and UserId = #userId;
But that has the disadvantage of returning one row for however many records you have. This could be a lot, depending on the app and the context, and in any case you don't want to pull over data that you're not going to use.
I wouldn't recommend a CASE statement, because SELECT CASE EXISTS ([whatever]) THEN 1 END will still return one record, and your affected record count will be 1 even if no records exist.
The problem with your original SQL, by the way: The statement is incomplete. You're saying "if exists ..." but you never finish it with the equivalent of a "then". You need to say "if exists() select 1" or something similar.