How to compare if BigDecimal value is inside a range in a query? - sql

Lets say that I have to check in a query if a value is inside a range, and this value is BigDecimal in Java. The values inside the database are numbers(with two decimals). The ideia is above...but I don´t know the right way and to make it a little worst, I don´t have access to test the query apart. I´m using jpa extended repository, so probably I need to write my own query in this case.
#Query("SELECT c "
+ " FROM Taxes c "
+ " WHERE c.minOrderValue <= 'Mvalue' AND c.maxOrderValue >= 'Mvalue' "
)
Optional<TaxesRR> getTaxes(#Param("Mvalue") BigDecimal Mvalue);

That´s how it´s worked for me. Any other solution is still appreciated.
#Query("SELECT c "
+ " FROM ConjuntoTaxasRetencaoRapida c "
+ " WHERE c.valorMinimoPorteFaturamento <= ?1 "
+ " AND c.valorMaximoPorteFaturamento > ?2")
Optional<ConjuntoTaxasRetencaoRapida> obterTaxasRR(BigDecimal valorProjetadoMes, BigDecimal valorProjetadoMesConsolidado);

Related

Using sub-select in FROM clause inside JPA #NamedQuery

In my app I need to use #NamedQuery to find the type of the most frequent operation assigned to specific account
#Entity
#Table(name="\"ACCOUNTOPERATION\"")
#NamedQuery(name="AccountOperation.findTypeOfMostFrequentOperation", query="" +
"SELECT ao.type from AccountOperation ao WHERE ao.account.id = ?1 " +
"GROUP BY ao.type HAVING COUNT(ao) = (" +
"SELECT MAX(typeCountQuery.typeCount) " +
"FROM (" +
"SELECT COUNT(aop) as typeCount " +
"FROM AccountOperation aop WHERE aop.account.id = ?1 GROUP BY aop.type" +
") as typeCountQuery" +
")"
)
public class AccountOperation {
#ManyToOne
private Account account;
private BigDecimal amount;
private OperationType type;
...
Right after FROM clause at '(' character, which begins typeCountQuery's body I'm getting
')', ',', GROUP, HAVING, IN, WHERE or identifier expected, got '('
I've read that JPA does not support sub-selects in the FROM clause, so is there any way to rewrite SQL code to still use it in #NamedQuery?
I'm using IntelliJ IDE with H2 DB and with eclipselink and javax.persistence in dependencies.
Link to source
In JPQL, you cannot use subqueries. To resolve this issue, you need to use some keywords like ALL, ANY, which work similiar.
So in your situation it could be:
#NamedQuery(name="AccountOperation.findTypeOfMostFrequentOperation", query="" +
"SELECT ao.type from AccountOperation ao WHERE ao.account.id = ?1 " +
"GROUP BY ao.type HAVING COUNT(ao) >= ALL (" +
"SELECT COUNT(aop) as typeCount " +
"FROM AccountOperation aop WHERE aop.account.id = ?1 GROUP BY aop.type)"
The type with a highest count returns the following query
select type
from AccountOperation
where id = ?
group by type
order by count(*) desc
fetch first 1 ROWS only
You should be anyway avare of the existence of ties, i.e. more types with the identical maximal count and should make some thought how to handle them.
I.e. in Oracle you may say fetch first 1 ROWS WITH TIES to get all the types with tha maximal count.

Query to select next few rows

I'm working on a search tool, the words (to be searched) are in object array
first i search the database(about 450k rows) using FTS4 and sqlite. This works fast, the SQL im using is:
String s = "select * from fts_sggs where word_text MATCH ? ";
but then, i need some extra words which are a part of the same table.
The FTS4 doesnt seem to work here.the sql is
String s ="select * from fts_sggs where word_number BETWEEN " + wordnumlo + " AND " + wordnumhi + " and page_number =" + pgnum;
im a newbie to SQL Programming, I need a single query that could perform both tasks fast. this is being done in java which is terribly slow.

Access: Runtime error 3075 (missing operator) in SQL update query

First time using Access and wanted to make an update query that uses a variable for its table name. Now, I've gotten myself into a web of nothing good. When I get to the part the SQL code is needed for, I get Runtime error 3075 - Missing operator in '(((" + enteredid + ".todayDate)=Format(Now()','""Short Date"")))' I've never coded in SQL, so I have no clue what operators are needed.
My code:
strSQL = "UPDATE " + enteredid + " SET " + enteredid + ".signIn = Format(Now(),""Short Time"") WHERE (((" + enteredid + ".todayDate)=Format(Now()','""Short Date"")));"
My suggestions:
You can avoid the whole Format() issue in the WHERE clause by using the Date() function instead of trying to extract just the date part of Now().
Since you are doing an UPDATE on a single table you can just use the field (column) names without the TableName. prefix.
To make your code more robust, enclose the table name in square brackets so it won't crash if the table name contains spaces or other "funny" characters.
So, the revised code would look more like this:
strSQL = _
"UPDATE [" + enteredid + "] SET " + _
"signIn = Format(Now(),""Short Time"") " + _
"WHERE todayDate = Date()"

How do I get around this common SQL problem

Haven't come across this in ages and when I searched for the solution I couldn't find one. I think its called overloading in SQL. Basically when I have "" (an empty string) for any parameter in this SQL I don't want to set a value in the database...
NOTE: I want to do it at a SQL level not do it at a C# level because its sloppy that way.
string Sql = "IF NOT EXISTS (SELECT * FROM tbl_FileSystemReferences) "
+ "INSERT INTO tbl_FileSystemReferences (UploadDir) VALUES (null) "
+ "UPDATE tbl_FileSystemReferences SET "
+ "UploadDir=#UploadDir, "
+ "ThumbnailDir=#ThumbnailDir, "
+ "ArchiveDir=#ArchiveDir, "
+ "RealDir=#RealDir, "
+ "FlashDir=#FlashDir, "
+ "AssociatedFilesDir=#AssociatedFilesDir, "
+ "EnableArchiving=#EnableArchiving, "
+ "AppWideDir=#AppWideDir, "
+ "FFmpegDir=#FFmpegDir, "
+ "InstallationDir=#InstallationDir ";
SqlCommand Command = new SqlCommand(Sql);
Command.Parameters.AddWithValue("#UploadDir", f.UploadDir);
Command.Parameters.AddWithValue("#ThumbnailDir", f.ThumbnailDir);
Command.Parameters.AddWithValue("#ArchiveDir", f.ArchiveDir);
Command.Parameters.AddWithValue("#RealDir", f.RealDir);
Command.Parameters.AddWithValue("#FlashDir", f.FlashDir);
Command.Parameters.AddWithValue("#AssociatedFilesDir", f.AssociatedFilesDir);
Command.Parameters.AddWithValue("#EnableArchiving", f.EnableArchiving);
Command.Parameters.AddWithValue("#AppWideDir", f.AppWideDir);
Command.Parameters.AddWithValue("#FFmpegDir", f.FFmpegDir);
Command.Parameters.AddWithValue("#InstallationDir", f.InstallationDir);
ExecuteNonQuery(Command);
I know there is a way I used to do this with stored procedure I just cant remember how (I think it's called overloading)....
Cheers,
Can you create a stored procedure rather than passing the command as text?
That way you can break each of the lines like "UploadDir=#UploadDir," into its own variable and only add it to the command if it is not null or not empty string
one way would be on a stored procedure, where you would receive all those parameters, then before the query either:
you allow to pass null
you convert each parameter to null if they are empty as:
select #UploadDir = null where #UploadDir = ''
you would do that for all your parameters, then on update query:
IF NOT EXISTS (SELECT * FROM tbl_FileSystemReferences)
INSERT INTO tbl_FileSystemReferences (UploadDir) VALUES (null)
UPDATE tbl_FileSystemReferences SET
UploadDir=coalesce(#UploadDir, UploadDir),
ThumbnailDir=coalesce(#ThumbnailDir, ThumbnailDir),
ArchiveDir=coalesce(#ArchiveDir, ArchiveDir),
RealDir=coalesce(#RealDir, RealDir),
FlashDir=coalesce(#FlashDir, FlashDir),
AssociatedFilesDir=coalesce(#AssociatedFilesDir, AssociatedFilesDir),
EnableArchiving=coalesce(#EnableArchiving, EnableArchiving),
AppWideDir=coalesce(#AppWideDir, AppWideDir),
FFmpegDir=coalesce(#FFmpegDir, FFmpegDir),
InstallationDir=coalesce(#InstallationDir, InstallationDir)

Convert SQL to HQL?

How can I convert the following SQL query into HQL?
SELECT count(sa.AID)
FROM A sa
, B sal,C m
WHERE sa.AID = sal.AID(+) and sa.BID = m.BID and sa.AID ='0001'
You need to transfer each table/column into it's associated Entity/Class in JAVA, then build the query with Hibernate ORM as below.
Suppose
- The entity name for the table sa is saEntity, for the table B is bEntity, and for the table C is cEntity.
- The class name for the column AID is AidClass, and for the column BID is BidClass
Then the Hibernate ORM query can be written as per the following (I like formating HQL queries inside annotations on multiple lines to make it easier to read & adapt).
#Query( "SELECT COUNT(sa.AidClass) "
+ "FROM saEntity sa, "
+ " bEntity sal "
+ " cEntity m"
+ "WHERE sa.AidClass = sal.AidClass"
+ " AND sa.BidClass = m.BidClass "
+ " AND sa.AidClass ='0001'")
public List <?> runMyQueryMethod();
Try looking at the answer to this question.
HQL to SQL converter
Or this article may help..
https://forum.hibernate.org/viewtopic.php?t=972441
If you showed some of the mappings I could probably help with the HQL. You could just use
Session.CreateSQLQuery instead??