First all I sorry on my english.
I development in gwt and I have appengine server.
I have question
1) how I can select row by date.
I write this
String query = "select key from " + MyClass.class.getName();
Query q = pm.newQuery(query);
String filter = "date<= 'Tue Mar 04 19:34:12 IST 2014'";
q.setFilter(filter);
int totalAgendaToNextWeekCounter += ((List<Integer>) q.execute()).size();
but is not work i get always 0.
thank you everybody
It will help to convert the date parameter from a string to a java.util.Date, and pass it as a query parameter, in something like:
Query q = pm.newQuery(query);
int totalAgendaToNextWeekCounter = 0;
try {
java.text.DateFormat dateformat = java.text.DateFormat.getDateInstance();
java.util.Date paramDate = dateformat.parse("2014-03-04T19:34:12");
String query = "select key from " + MyClass.class.getName();
q.setFilter( "date <= :paramDate" );
totalAgendaToNextWeekCounter = ((List<Integer>) q.execute(paramDate)).size();
}
catch (java.text.ParseException ex) {
java.util.logging.Logger.getLogger(logName).severe("");
}
finally {
q.closeAll();
}
This may not fit exactly in your program, but the important thing is not to pass the date parameter as a string.
Related
I'm working through a stored procedure and wondering if there's a way to retrieve the anticipated result column list from a sql statement before fully executing.
Scenarios:
dynamic SQL
a UDF that might vary the columns outside of our control
EX:
//inbound parameter
SET QUERY_DEFINITION_ID = 12345;
//Initial statement pulls query text from bank of queries
var sqlText = getQueryFromQueryBank(QUERY_DEFINITION_ID);
//now we run our query
var cmd = {sqlText: sqlText };
stmt = snowflake.createStatement(cmd);
What I'd like to be able to do is say "right - before you run this, give me the anticipated column list" so I can compare it to what's expected.
EX:
Expected: [col1, col2, col3, col4]
Got: [col1]
Result: Oops. Don't run.
Rationale here is that I want to short-circuit the execution if something is missing - before it potentially runs for a while. I can validate all of this after the fact, but it would be really helpful to stop early.
Any ideas very much appreciated!
This sample SP code shows how to get a list of columns that a query will project into the result before you run the query. It should only be used for large, long running queries because it will take a few seconds to get the column list.
There are a couple of caveats. 1) It will only return the names of the columns. It won't tell you how they were built, that is, whether they're aliased, direct from a table, calculated, etc. 2) The example query I used is straight from the Snowflake documentation here https://docs.snowflake.com/en/user-guide/sample-data-tpcds.html#functional-query-definition. For convenience, I minimized the query to a single line. The output of the columns includes object qualifiers in addition to the column names, so V1.I_CATEGORY, V1.D_YEAR, V1.D_MOY, etc. If you don't want them to make it easier to compare names, you can strip off the qualifiers using the JavaScript split function on the dot and take index 1 of the resulting array.
create or replace procedure EXPLAIN_BEFORE_RUNNING()
returns string
language javascript
execute as caller
as
$$
// Set the context for the session to the TPC-H sample data:
executeNonQuery("use schema snowflake_sample_data.tpcds_sf10tcl;");
// Here's a complex query from the Snowflake docs (minimized to one line for convienience):
var sql = `with v1 as( select i_category, i_brand, cc_name, d_year, d_moy, sum(cs_sales_price) sum_sales, avg(sum(cs_sales_price)) over(partition by i_category, i_brand, cc_name, d_year) avg_monthly_sales, rank() over (partition by i_category, i_brand, cc_name order by d_year, d_moy) rn from item, catalog_sales, date_dim, call_center where cs_item_sk = i_item_sk and cs_sold_date_sk = d_date_sk and cc_call_center_sk= cs_call_center_sk and ( d_year = 1999 or ( d_year = 1999-1 and d_moy =12) or ( d_year = 1999+1 and d_moy =1)) group by i_category, i_brand, cc_name , d_year, d_moy), v2 as( select v1.i_category ,v1.d_year, v1.d_moy ,v1.avg_monthly_sales ,v1.sum_sales, v1_lag.sum_sales psum, v1_lead.sum_sales nsum from v1, v1 v1_lag, v1 v1_lead where v1.i_category = v1_lag.i_category and v1.i_category = v1_lead.i_category and v1.i_brand = v1_lag.i_brand and v1.i_brand = v1_lead.i_brand and v1.cc_name = v1_lag.cc_name and v1.cc_name = v1_lead.cc_name and v1.rn = v1_lag.rn + 1 and v1.rn = v1_lead.rn - 1) select * from v2 where d_year = 1999 and avg_monthly_sales > 0 and case when avg_monthly_sales > 0 then abs(sum_sales - avg_monthly_sales) / avg_monthly_sales else null end > 0.1 order by sum_sales - avg_monthly_sales, 3 limit 100;`;
// Before actually running the query, generate an explain plan.
executeNonQuery("explain " + sql);
// Now read the column list from the explain plan from the result set.
var columnList = executeSingleValueQuery("COLUMN_LIST", `select "expressions" as COLUMN_LIST from table(result_scan(last_query_id())) where "operation" = 'Result';`);
// For now, just exit with the column list as the output...
return columnList;
// Your code here...
// Helper functions:
function executeNonQuery(queryString) {
var out = '';
cmd = {sqlText: queryString};
stmt = snowflake.createStatement(cmd);
var rs;
rs = stmt.execute();
}
function executeSingleValueQuery(columnName, queryString) {
var out;
cmd1 = {sqlText: queryString};
stmt = snowflake.createStatement(cmd1);
var rs;
try{
rs = stmt.execute();
rs.next();
return rs.getColumnValue(columnName);
}
catch(err) {
if (err.message.substring(0, 18) == "ResultSet is empty"){
throw "ERROR: No rows returned in query.";
} else {
throw "ERROR: " + err.message.replace(/\n/g, " ");
}
}
return out;
}
$$;
call Explain_Before_Running();
Can someone help me? I have created method for getting data from a stored procedure in this procedure user select month year and district and it will show numbers of user on that district, it is working fine on localhost but when I upload this to the server, it is no longer working properly.
[HttpPost]
public ActionResult get_Data_with_months(int did, string month, string year)
{
string dateset = "01" + "/" + month + "/" + year;
//string dateset = month + "/01/" + year;
DateTime date = Convert.ToDateTime(dateset);
DateTime firstDayOfMonth = new DateTime(date.Year, date.Month, 1);
DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
// string second = Did;
string first = Convert.ToDateTime(firstDayOfMonth).ToString("MM/dd/yyyy");
string last = Convert.ToDateTime(lastDayOfMonth).ToString("MM/dd/yyyy");
var Monthwisetkt = db.spWitnessDataMonthwise(first, last, did).ToList();
ViewBag.count = Monthwisetkt.Count;
//Creating table for response data
StringBuilder DistrictTbl = new StringBuilder();
int count = 1;
int j = 0;
//DistrictTbl.Append("<b>"+ month + year+ "Witness List</b>");
DistrictTbl.Append("<div class='col-md-12 m-auto'><table class='table table-bordered' id='tbl-data'><thead><tr><th>S.No.</th><th>District Name</th><th>No of Witness </th></tr></thead><tbody>");
foreach (var item in Monthwisetkt)
{
var DistrictName = Monthwisetkt.ElementAt(j).District_name;
var no_of_witness = Monthwisetkt.ElementAt(j).NoOfWitness;
DistrictTbl.Append("<tr><td>"+ count + "</td><td>"+ DistrictName + "</td><td>"+ no_of_witness + "</td></tr>");
j++;
count++;
}
DistrictTbl.Append("</tbody></table></div>");
return Json(new { result = "True", msg = DistrictTbl.ToString() });
}
Stored procedure:
ALTER PROCEDURE [dbo].[spWitnessDataMonthwise]
(#fromDate nvarchar(50),
#toDate nvarchar(50),
#DistrictId int)
AS
SELECT
id, District_name,
(SELECT COUNT(*)
FROM WHD_witness
WHERE District_Name = dtable.id
AND insert_date BETWEEN #fromDate AND #toDate
AND dtable.id = #DistrictId) AS NoOfWitness
FROM
WHD_district dtable
WHERE
dtable.id = #DistrictId
The porblem is that server is taking date in yyyy-mm-dd format so i changed format of my input string which is passing to my function.
I have one requirement in which i have to insert record in one table and update the record in another table.
There are 100 records for which i have to do above insertion and updation.
But If any record fails due to any error in insertion or updation only that record should be rollback not others.Means if There are 100 records and 60 gets success and 61 gets fails due to any error then only 61 records should be rolled back not all other 60 records.
I am using Spring boot JPA and #Transactional Annotation.But if put this annotation on starting of my method,Then in case of any error it roll back all records.
I am attaching my code below.Please suggest how i can achieve this.
In below code i have persistRecord() method which have all my code for insertion and updation.I have not marked this with #Transactional annotation insteed below method is annotated with #Transactional annotation
logger.debug("insertSalesTargetData method called of service class");
String userid = (String) webSession.getAttribute("username");
logger.debug("Userid :" + userid);
HashMap<String, String> persistRecordStatus = new HashMap<String, String>();
Query qCountCheck = em.createNativeQuery(QueryConstant.CHECK_SALES_TARGET_DATA_QUERY);
List<Object> existingRecordList = null;
persistRecordStatus.put("TOTAL_RECORD", String.valueOf(xlsRowslist.size()));
int failedRecordCount = 0;
int successRecordCount = 0;
for (int i = 0; i < xlsRowslist.size(); i++) {
ArrayList rowList = xlsRowslist.get(i);
// try {
double weekNoDouble = Double.parseDouble((String) rowList.get(0));// Week No
String fromDate = (String) rowList.get(1);// fromDate
String toDate = (String) rowList.get(2);// toDate
double catCodeDouble = Double.parseDouble((String) rowList.get(3));// catCode
int catCode = (int) catCodeDouble;
int weekNo = (int) weekNoDouble;
String target = (String) rowList.get(4);// target
String salesGoalId = fromDate + toDate + catCode;
salesGoalId = salesGoalId.replace("-", "");
// Check if the sales goal id already exist in the database or not
qCountCheck.setParameter(1, salesGoalId);// SALES_GOAL_ID
existingRecordList = qCountCheck.getResultList();
logger.debug("Count List Size " + existingRecordList.size());
if (existingRecordList != null && existingRecordList.size() > 0) {
if (existingRecordList.get(0) != null) {
BigDecimal row = (BigDecimal) existingRecordList.get(0);
// try {
logger.debug("Persisting record no " + i);
persistRecord(row, salesGoalId, target, fromDate, toDate, userid, catCode, weekNo);
logger.debug("Record no " + i + " persisted");
persistRecordStatus.put("SUCCESS_RECORD", String.valueOf(successRecordCount++));
/*
* } catch (Exception e) { persistRecordStatus.put("FAILED_RECORD",
* String.valueOf(failedRecordCount++)); }
*/
}
} else {
persistRecordStatus.put("FAILED_RECORD",String.valueOf(failedRecordCount++));
}
/*
* } catch (Exception e) { logger.debug("Exception in processing record no " + i
* + " " + e.toString()); persistRecordStatus.put("FAILED_RECORD",
* String.valueOf(failedRecordCount++)); }
*/
}
return persistRecordStatus;
}
You are doing some kind of batch updates ?
In batch processing, you treat "failures" by putting all stuff involved (e.g. the input record, an error code, ...) on an error store for subsequent review by some user. And you commit that along with all the "successful" updates.
Alternatively, put each insert/update pair in its own transaction. (and still alternatively, if your DBMS / transactional framework supports savepoints, take a savepoint after each insert/update pair and upon failure, rollback to the last savepoint and then commit (and figure out a way to not lose the remaining 40 unprocessed entries from your input). In either case, don't come complaining if you get performance trouble.
There is no having things both ways in transactional batch processing.
I´m trying to optimize some process in my application but I´m stuck with this problem. My application is working so the entity mapping is correct. Simplifying what I´m trying to do is this:
using (var offCtx = new CheckinOfflineEntities())
{
using (var trans = offCtx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
DateTime purgePivot = DateTime.Now.AddDays(-2);
count = offCtx.Database.ExecuteSqlCommand(#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= {0}", purgePivot);
long d = offCtx.Database.SqlQuery<long>("select count(*) from #NewLegs").FirstOrDefault();
}
}
I´m selecting some data I want to delete from one table, storing it in a temporary table so that I can use this temporary table in other queries to exclude related data.
The problem is, when I try to use the temporary table I´m receiving the exception SqlException: "Invalid object name '#NewLegs'."
Thank you for your time.
You can merge the query like this.
And count returns int, not long.
COUNT always returns an int data type value. - MSDN
var query = string.Format("{0} {1}",
#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= #STDUTC",
#"select count(*) from #NewLegs")
var d = offCtx.Database.SqlQuery<int>(query, new SqlParameter("STDUTC", purgePivot))
.FirstOrDefault();
I realy don´t know why but removing the parameter and adding it in the query solved the problem.
The code below works fine:
using (var offCtx = new CheckinOfflineEntities())
{
using (var trans = offCtx.Database.BeginTransaction(IsolationLevel.Snapshot))
{
DateTime purgePivot = DateTime.Now.AddDays(-2);
count = offCtx.Database.ExecuteSqlCommand(#"select L.* into #NewLegs from InventoryLeg L where L.STDUTC >= " + purgePivot.toString("yyyy-mm-dd HH:mm:ss");
long d = offCtx.Database.SqlQuery<long>("select count(*) from #NewLegs").FirstOrDefault();
}
}
I want to do search in my database using some fields filled by a form
but if some fields are left empty i don't want to include them
which kind of query can help me in achieving this??
Currently i am using a query like:
Select * from DATABASE where COLUMN='form_input';
but as my form will return empty it will try and select rows which have null entries but rather i want to this time see a result of all rows in database i.e i want to invalidate the filter by COLUMN='form_input'
As we do not know your server side scripting language -
The psheuducode should be -
if(request['form_input']!=null)
Select * from DATABASE where COLUMN='form_input';
else
Select * from DATABASE;
Also If there are many fields for form_input then we can design
our code something like -
String wherequery = "";
if(request['form_input1']!=null)
{
wherequery = wherequery + " COLUMN='form_input1' ";
}
if(request['form_input2']!=null)
{
wherequery = wherequery + " And "
wherequery = wherequery + " COLUMN='form_input2' ";
}
if(request['form_input3']!=null)
{
wherequery = wherequery + " And "
wherequery = wherequery + " COLUMN='form_input3' ";
}
....
And so on
....
String selectQuery = "";
if(wherequery == "")
{
selectQuery = "Select * from TABLE";
}
else
{
selectQuery = "Select * from TABLE where" + wherequery ;
}
execute (selectQuery);
Please note we are using pseudo code here. We can take the form inputs and concatenate query for each input which is not null.
If we find the concatenated string as blank string, we will select the full table.
Otherwise
we will select with the where clause query.
Hope, this help you out.