Store Groovy SQL result as a variable? - sql

I am very, very new to Groovy (like two days in). I am trying to take a SQL result which will return a single value, and store that value so that it can be put in the body of an email. However, my SQL result always returns NULL, but the other values in the email work just fine.
I know that the result will only return a single value, so how in the world can I get that value stored as a string?
def sql = getSqlInstance()
def user = "\'" + trmCurrentUser.username + "\'";
def name = "\'" + trmCurrentUser.displayname + "\'";
def email = "\'" + trmCurrentUser.email + "\'";
def comm = "\'" + trmComponent.id + "\'";
def rslt=[];
def cmpgn;
rslt[0] = sql.firstRow("select activity_id from DB.TABLE where communication_id=${comm}");
def cmpgn = rslt[0];
toAddress = trmCurrentUser.email;
fromAddress = "me#email.com";
trmUtilities.sendEmail (
//self explanatory
toAddress, fromAddress,
//body of email
user + " " + name + " " + email + " " + comm + " " + cmpgn[0],
//subject of email
" Action on " + trmComponent.componentType + " " + trmComponent.name
);
The resulting email I get is this (with the appropriate values other than the NULL):
'MYID' 'MY NAME' 'MYEMAIL' 'COMM' null

Related

How to pass multiple values in a native query and retrieve that data in a Map<String, List<Data>>?

Here I want to pass a list of Ids and date as a parameter to the database query and I want the query to return data in a Map so the key is the id and List is the data against that id.
Query<Data> query = rdsSession.createNativeQuery(DBQueries.DATA_QUERY,
Data.class).setParameterList("performance_id", listOfIds).setParameter("fromdate", fromDate);
List<Data> listDBRecords = null;
Map<String, List<Data> records=listDBRecords.stream().collect(Collectors.groupingBy(Data::getId));
So how can I achieve this result by passing multiple values(ie. ids) in the query and return that data? This is the query I have written
public static final String SELECT_PORTFOLIO_SECURITY_DATA = "select capl.corporate_action_portfolio_level_id, " +
"capl.performance_id, capl.forwardlooking_sequence_no, " +
"capl.as_of_date, capl.price, casl.currency, capl.exchange_rate, " +
"capl.gross_dividend, capl.net_dividend, capl.sub_portfolio_guid, capl.effective_date, capl.adjustment_weighted_factor, capl.price_adjustment_factor, " +
"casl.share_adjustment_factor, casl.float_adjustment_factor, capl.index_shares, capl.input_tos_live, casl.input_float_live, capl.prediction_type from " +
ConfigurationManager.getProperties().getProperty("rdsConnection.schema") +
".corporate_action_portfolio_level capl inner join " +
ConfigurationManager.getProperties().getProperty("rdsConnection.schema") +
".corporate_action_security_level casl " +
"on capl.performance_id = casl.performance_id and capl.as_of_date = casl.as_of_date and capl.prediction_type = casl.prediction_type and " +
"capl.forwardlooking_sequence_no = casl.forwardlooking_sequence_no " +
"where capl.performance_id = :performance_id and capl.as_of_date = :as_of_date and capl.prediction_type = 'PREDICTED' or capl.prediction_type = 'LIVE'";
Can someone tell what is the right way?

Dynamic dates in where parameter

Am I able to use a dynamic date range for the "where" parameter? I'd like to get all the data changed in the last 30 mins.
All I can find in the documentation is using static dates:
https://developer.xero.com/documentation/api/requests-and-responses
You could try using the query string in the Where Clause.
For Ex.
string querystr = "Date >= " +
"DateTime(" + dateFrom.Year.ToString() + ",
" + dateFrom.Month.ToString() + ", " + dateFrom.Day.ToString() + ") " +
"&& Date <= " +
"DateTime(" + dateTo.Year.ToString() + ", "
+ dateTo.Month.ToString() + ", " + dateTo.Day.ToString() + ")";
Passing this querystring to retrieve user defined date rage Invoices

SQL Join Query taking long to complete

I am working on a project that require me to join four tables. I have written this code but it's taking forever to finish. Please help. Ohhh I have about 121 000 entries in the Db
PortfolioCollectionDataContext context = null;
context = DataContext;
var Logins = from bkg in context.EnquiryBookings
where bkg.Paid == true
from log in context.Logins
where log.LoginID == bkg.LoginID
from enq in context.Enquiries
where enq.EnquiryID == bkg.EnquiryID
from estb in context.Establishments
where enq.EstablishmentID == estb.EstablishmentID
select new
{
log.LoginID,
log.FirstName,
log.LastName,
log.CountryOfResidence,
log.EmailAddress,
log.TelephoneNumber,
bkg.TotalPrice,
estb.CompanyName
};
string str = "";
foreach (var user in Logins)
{
str += ("[Name: " + user.LastName + " " + user.FirstName + " - Country: " + user.CountryOfResidence + " - Phone: " + user.TelephoneNumber + " - Email: " + user.EmailAddress + " - Booked From: " + user.CompanyName + " - Spent: " + user.TotalPrice.ToString() + "]");
}
return str;
Use following query on LINQ
PortfolioCollectionDataContext context = null;
context = DataContext;
var Logins = from bkg in context.EnquiryBookings
join log in context.Logins
on log.LoginID equals bkg.LoginID
&& bkg.Paid == true
join enq in context.Enquiries
on enq.EnquiryID equals bkg.EnquiryID
join estb in context.Establishments
on enq.EstablishmentID == estb.EstablishmentID
select new
{
str = "[Name: " + log.LastName + " " + log.FirstName + " - Country: " + log.CountryOfResidence + " - Phone: "
+ log.TelephoneNumber + " - Email: " + log.EmailAddress + " - Booked From: "
+ estb.CompanyName + " - Spent: " + bkg.TotalPrice.ToString() + "]"
};
string output = string.Join(", ", Logins.ToList());
return output;
Check your query by taking cursor on Logins and paste that query here. Then check an estimated execution plan of your query and paste here.
If using SQL Server, to get execution plan of your query using Sql server management studio, click on an icon highlighted in an image below.

Pass a SQL condition as a OleDb parameter

I have following code:
Dim executedCmd As OleDb.OleDbCommand = m_dbMgr.GetCommand()
executedCmd.CommandText = "select * from [Parameters] where "
Dim SQLcondition As String = String.Empty
For i As Integer = 0 To ParameterName.Count - 1
executedCmd.CommandText += "ParameterName = #parametername" + i.ToString() + " and ParameterValue #ParamaterCondition" + i.ToString() + " #ParameterValue" + i.ToString()
executedCmd.Parameters.AddWithValue("#parametername" + i.ToString(), ParameterName(i))
executedCmd.Parameters.AddWithValue("#ParameterValue" + i.ToString(), ParameterValue(i))
executedCmd.Parameters.AddWithValue("#ParamaterCondition" + i.ToString(), Condition(i))
Next
ParameterName, ParameterValue, ParameterCondition all are same length ArrayList, but the code does not work properly. I have verified all the variables have values.
When I run the code it reports a syntax error: "missing operations in query expression"
The problem is that ParameterCondition has values like ('>', '<', '=',.... some logical SQL operators).
Edit: How can I include conditions in parameters?
Add 1 = 1 after where to simplify building logical expression. Notice that all conditions added by AND logical operator. You can generate parameter name from columns name.
executedCmd.CommandText = "select * from [Parameters] where 1 = 1"
....
executedCmd.CommandText += " AND " + ParameterName(i) + " " + Condition(i) + " #" + ParameterName(i)
executedCmd.Parameters.AddWithValue("#" + ParameterName(i), ParameterValue(i))
ParameterCondition must all be binary operators.
The database engine would check the syntax of the SQL statement before it replaces the parameters with values. So somethinhg like "WHERE #p1 #p2 #p3" will not be parsed correctly.
Replace your condition with a string-expression e.g.
commandtext = parameterName + condition + " #p1"

'IN' query in fusion table

In the following code, i want to add "IN" +Village+. Where to add this condition in the code. Variable village takes value from a drop down list based on that filter should occur.please help me.Village name is a column in my fusion table.
i.e select 'geometry',villageName from table where querypass > textvalue IN villagename='madurai'
function querymape()
{
/*variable holds the value*/
var village =document.getElementById('village').value.replace(/'/g, "\\'");
var operatore=document.getElementById('operatorstringe').value.replace(/'/g, "\\'");
var textvaluee=document.getElementById("text-valuee").value.replace(/'/g, "\\'");
var querypasse=document.getElementById('query-passe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypasse + " FROM " + tableid + " WHERE " + querypasse + " " + operatore + " '" + textvaluee + "'"+"AND 'VillageName=+village+'");
}
}
/*This is my new code.But its not working.Please help me*/
function querymap()
{
//var villagename='';
var operator=document.getElementById('operatorstring').value.replace(/'/g, "\\'");
var textvalue=document.getElementById("text-value").value.replace(/'/g, "\\'");
var querypass=document.getElementById('query-pass').value.replace(/'/g, "\\'");
var searchStringe = document.getElementById('Search-stringe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypass + " FROM " + tableid + " WHERE " + querypass + " " + operator + " '" + textvalue + "'"+"AND 'VillageName'="+ searchStringe+"");
}
}
Multiple conditions can be combined using the keyword "and"?
You twisted the IN syntax around, it is used when you want to match several values, if you only want to compare to a single value use "=" instead
Applied to your query (with IN syntax):
select 'geometry',villageName from table where querypass > textvalue and villagename IN ('madurai','another village')
With = syntax:
select 'geometry',villageName from table where querypass > textvalue and villagename = 'madurai'