Postgres datatype conversion differ on Ubuntu and windows - windows

I am getting following exception on windows while running the below
ERROR: operator does not exist: numeric = character varying Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts." while executing with query parameter
I am passing the Numeric String for parameter using function as a named parameter to the query
getUIDCount(String id) {
...
select count(UID) as icrd FROM UID_tbl WHERE id = ?
...
}
where id is numeric(5,0)" in table
Everything works well on Ubuntu but getting Error while running the same code on windows. I have to do the explicit casting just for windows. I am using PostgreSQL 9.4.3. I am using "org.hibernate.dialect.PostgreSQLDialec" and grails 2.3.11 with runtime 'org.postgresql:postgresql:9.3-1100-jdbc41'
updated with how it is getting called
def Integer getUIDSetSize(String _id)
{
Integer i = 0;
Sql sql = new Sql(dataSource);
String sqlt = """select count(UID) as icrd FROM UID_tbl WHERE _id = ?""";
log.trace(sqlt);
sql.eachRow(sqlt, [_id], { row -> i = row.icrd; });
return i;
}
This how it get called def _id1 = params._id1; count1 = HelperService.getUIDSetSize(_id1)

The workaround for casting from varchar to numeric is
CREATE CAST(VARCHAR AS NUMERIC) WITH INOUT AS IMPLICIT;
This is not the best solution and would suggest selective casting from the code.

Related

how to use a custom Function in Oracle Statement on each value of one column using Scala

I have a Scala Function. I need to read records that their last two characters of ID column are equal to the result of func. So, I must use func in Oracle query which is in following:
def func(id:String): Int = {
val two_char = id.takeRight(2).toInt
val group_id = two_char % 4
return group_id
}
val query = """ SELECT * FROM table where """+func("ID") + """==="""+group_id
When Scala run the query, I receive this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "ID"
func pass name of column not its values. Would you please guide me how to use the function in Oracle Query to operate on each value of the column?
Any help is really appreciated.

Search sqlite3 table for an integer using C++

I have an sqliteCpp wrapper for my sqlite3 and was wondering if there is a query to search for integer in 'Symcod' columns as shown below:
sym = 100;
SQLite::Statement query(db, "SELECT Symcod FROM RawData WHERE EXISTS Symcod = sym");
but this gives me an Syntax error. Is there a way I can search the table for a integer using a variable name?
The sqlitecpp documentation suggests
// Compile a SQL query, containing one parameter (index 1)
SQLite::Statement query(db, "SELECT * FROM test WHERE size > ?");
// Bind the integer value 6 to the first parameter of the SQL query
query.bind(1, 6);
// Loop to execute the query step by step, to get rows of result
while (query.executeStep())
{
//.... do stuff with e.g. query.getColumn()
}
So you would construct your query using a ? for the variable, then do query.bind(1,sym)

Linq Query Message: Specified cast is not valid

Following are the columns name and its data type:
TemplateName string
TaskName string
AvgDays string (but contains int values)
my LINQ query:
DataTable newTable = new DataTable();
newTable = (from r in table.AsEnumerable()
group r by r.Field<string>("TemplateName") into templates
let totalDays = templates.Sum(r => r.Field<int>("AvgDays"))
from t in templates
group t by new
{
TemplateName = templates.Key,
TaskName = t.Field<string>("TaskName"),
TotalDays = totalDays
} into tasks
select new
{
tasks.Key.TemplateName,
tasks.Key.TaskName,
AvgDays = tasks.Sum(r => r.Field<int>("AvgDays")),
tasks.Key.TotalDays
}).CopyToDataTable();
I am getting error after execution of query. Error is "Specified cast is not valid.".
Please let me know where am I doing wrong.
I guess Field<int> causes the problem, because the field is not really an int. As you said before, it's a string.
Try following
AvgDays = tasks.Sum(r => int.Parse(r.Field<string>("AvgDays"))),
Field<T> does not perform some magic transformation between different types. It's implemented like that:
return (T)((object)value);
In practice there is a little bit more code, but logic is the same. It just tried to cast your value to desired type, and as you probably know, casting string to int does not work.

Unable to create a constant value - only primitive types or Enumeration types allowed

I have seen some questions related to this Exception here but none made me understand the root cause of the problem. So here we have one more...
var testquery =
((from le in context.LoanEMIs.Include("LoanPmnt")
join lp in context.LoanPmnts on le.Id equals lp.LoanEMIId
where lp.PmntDtTm < date && lp.IsPaid == false
&& le.IsActive == true && lp.Amount > 0
select new ObjGetAllPendingPmntDetails
{
Id = lp.Id,
Table = "LoanEMI",
loanEMIId = lp.LoanEMIId,
Name = le.AcHead,
Ref = SqlFunctions.StringConvert((double)le.FreqId),
PmntDtTm = lp.PmntDtTm,
Amount = lp.Amount,
IsDiscard = lp.IsDiscarded,
DiscardRemarks = lp.DiscardRemarks
}).DefaultIfEmpty(ObjNull));
List<ObjGetAllPendingPmntDetails> test = testquery.ToList();
This query gives the following Exception Message -
Unable to create a constant value of type CashVitae.ObjGetAllPendingPmntDetails. Only primitive types or enumeration types are supported in this context.
I got this Exception after I added the SQL function statement to convert le.FreqId which is a byte to a string as ToString() is not recognized in the LINQ Expression Store.
ObjGetAllPendingPmntDetails is a partial class in my model which is added as it is used too many times in the code to bind data to tables.
It has both IDs as long, 'Amount' as decimal, PmntDtTm as Datetime,IsDiscard as bool and remaining all are string including 'Ref'.
I get no results as currently no data satisfies the condition. While trying to handle null, I added DefaultIfEmpty(ObjNull) and ObjNull has all properties initialized as follows.
ObjGetAllPendingPmntDetails ObjNull = new ObjGetAllPendingPmntDetails()
{ Id = 0, Table = "-", loanEMIId = 0, Name = "-", Ref = "-",
PmntDtTm = Convert.ToDateTime("01-01-1900"),
Amount = 0, IsDiscard = false, DiscardRemarks = "" };
I need this query to work fine as it has Union() called on it with 5 other queries. All returning the same ObjGetAllPendingPmntDetails columns. But there is some problem as this query has no data satisfying the conditions and the Exception Shared Above.
Any suggestions are appreciated as I am unable to understand the root cause of the problem.
#AndrewCoonce is right, the .DefaultIfEmpty(ObjNull) is the culprit here. Entity Framework turns DefaultIfEmpty into something like...
CASE WHEN ([Project1].[C1] IS NULL) THEN #param ELSE [Project1].[Value] END AS [C1]
...but there's no way to coerce an instance of ObjGetAllPendingPmntDetails into something that can take the place of #param, so you get an exception.
If you move the DefaultIfEmpty call to after the ToList it should work correctly (although you'll need to call ToList again after that if you really want a concrete list instance).

what are the OleDbTypes associated with Oracle Number and varchar2 when calling a function

I'm trying to map OleDb parameters to an Oracle Function. I was able to do this using the System.Data.Oracle namespace but then found that this is depricated, so I thought i would re-write it as OldDb to avoid installing the Oracle Provider.
I have defined the following oracle function as an example:
create function GetImagePath (AIRSNumber in number)
return varchar2
is
begin
return '\\aiimg524\images\Ofndrtrk\2010\01\0kvrv1p000lcs74j';
end;
and I'm calling it using the following code:
using (var command = new OleDbCommand())
{
command.Connection = con;
command.CommandText = ConfigurationManager.AppSettings[OTRAK_PHOTO_FUNC];
command.CommandType = CommandType.StoredProcedure;
string parm = ConfigurationManager.AppSettings[OTRAK_PHOTO_PARM];
command.Parameters.Add(parm, OleDbType.Decimal); // maps to oracle Number
command.Parameters[parm].Direction = ParameterDirection.Input;
command.Parameters[parm].Value = airsNumber;
command.Parameters.Add(RETURN_VALUE, OleDbType.Variant); // maps to Oracle varchar2
command.Parameters[RETURN_VALUE].Direction = ParameterDirection.ReturnValue;
try
{
con.Open();
command.ExecuteNonQuery();
path = command.Parameters[RETURN_VALUE].Value.ToString();
}
I tried a bunch of different OleDB types for the parameter and the return value. the current attempt is from a mapping table i found on the web that said number = decimal and varchar2 = variant. I'm about to try every permutation of types in the enum and wanted to ask for help. the not so useful error message i get is:
[System.Data.OleDb.OleDbException] = {"ORA-06550: line 1, column 7:\nPLS-00306: wrong number or types of arguments in call to 'GETIMAGEPATH'\nORA-06550: line 1, column 7:\nPL/SQL: Statement ignored"}
This actually had nothing to do with the type of the parameters but the order. Using the OleDb provider for Oracle does not respect the names of the parameters in the parameter collection but rather the order that the parameters are added. Wwhen calling an oracle function, the return value is a free parameter that must be declared first. by adding my return value parameter and then the actual function parameter things started working.
using the command.Parameters.AddWithValue(parm, value) also simplifies things a bit.

Resources