nhibernate CreateCriteria wildcard Like when - nhibernate

In SQL I can write
SELECT blah FROM Clients
Where #p1 Like '%'+lastname+'%'
How do I represent this with CreateCriteria in Nhibernate?
I've tried s.CreateCriteria<Client>.Add(Restrictions.Where<Client>(c => "something".Contains(c.LastName))
but get an error
System.Exception: Unrecognised method call: System.String:Boolean Contains(System.String)\r\n at NHibernate.Impl.ExpressionProcessor.ProcessCustomMethodCall(MethodCallExpression methodCallExpression)
I've also tried
s.CreateCriteria<Client>.Add(Restrictions.Where<Client>(c => "something".IndexOf(c.LastName) != -1))
but get
"variable 'c' of type 'TrinityFinance.Data.Entities.Client' referenced from scope '', but it is not defined"
Note the order is important here.
#p1 Like '%'+lastname+'%'
is not the same as
lastname Like '%'+#p1+'%'

s.CreateCriteria<Client>().Add(
Restrictions.InsensitiveLike( "LastName", "something", MatchMode.Anywhere))

Thanks to a friend I've solved my issue.
var searchCriteria = GetSession().CreateCriteria<Client>();
searchCriteria.Add(Expression.Sql(string.Format("'{0}' like '%' + {1} + '%'", p.ClientInputText,p.DbField)));
var results = searchCriteria.List<Client>();

For Case-Insensitive %Like% Search
Criteria criteria = session.createCriteria(Any.class);
criteria.add(Restrictions.ilike(propertyName, value, MatchMode.ANYWHERE);
criteria.list();

Related

Oracle and Nodejs - can't bind parameters in SQL statement

Hi I have the following statement that I execute using node-oracle
await connection.execute(`SELECT * FROM TABLE WHERE NAME LIKE '%And%'`)
But now I want to bind a parameter instead of using a hard coded value
const queryText = 'And';
await connection.execute(`SELECT * FROM TABLE WHERE NAME LIKE '%:queryText%'`, {queryText});
it throws Error: ORA-01036: illegal variable name/number
What is the correct way of binding a parameter here, since the documentation doesn't cover this situation?
Try with the following:
const queryText = 'And';
await connection.execute(
"SELECT * FROM TABLE WHERE NAME LIKE :queryText",
{
queryText: { dir: oracledb.BIND_IN, val: '%'+ queryText +'%', type: oracledb.STRING }
});
Use string concatenation:
SELECT * FROM TABLE WHERE NAME LIKE '%' || :queryText || '%'
Here is a working example.
let queryText = "John"
let sql = "SELECT * FROM TABLE WHERE NAME LIKE :queryText"
let binds = {queryTarget: {dir: oracledb.BIND_IN, val: queryText, type: oracledb.STRING}}
let result = await connection.execute(sql, binds, options)
Do not add '%' like the other people suggested.

NHibernate icriteria SQLFunction Left

How do i implement the following statement in NHibernate iCriteria
Select * From LECNNy where Left(Address,4)='test'
It has to be something like
Projections.SqlFunction("left"("Address"),
But how do i pass the number of chars and the var ?
Some further research gave the following answer :
store.Add(
Restrictions.Eq(
Projections.SqlFunction(
"left",
NHibernate.NHibernateUtil.String,
Projections.Property("Address"),
Projections.Constant(4)
),
'test'
)
);

Entity Framework and dynamic order by statements

I have been struggling to get this working. I wish to have an EF statement take in a column to order by. My original statement was this:
var Query = from P in DbContext.People
where P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId)
orderby P.LastName
select P;
And I changed this to the following:
var Query = from P in DbContext.People
where P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId)
orderby sortField
select P;
Where sortField is the column we wish to sort on, and is a string i.e. LastName. However, it does not appear to work, it does no sorting, and the outputted SQL string is completely wrong. Anyone got this working before?
you could try passing in an expression to your method with the following type:
Expression<Func<Person, object>> expr = p => p.LastName;
and then using linq extensions instead of linq expressions...
var Query =
DbContext.People
.Where(P => P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId))
.OrderBy(expr)
.ToList();
Your sort does not work because you are sorting on a string literal. It is not illegal, but it is not particularly useful either. You need to provide a sorting field through the API of IQueryable<T>, for example, like this:
var q = from P in DbContext.People
where P.BusinessUnits.Any(BU =>BU.BusinessUnitID == businessUnitId)
orderby P.LastName
select P;
if ("sortField".Equals("FirstName"))
q = q.OrderBy(p => p.FirstName);
else if ("sortField".Equals("LastName"))
q = q.OrderBy(p => p.LastName);
else if ("sortField".Equals("Dob"))
q = q.OrderBy(p => p.Dob);

PetaPoco: How to use the SQL Like keyword ( WHERE Name LIKE '%#0%')

What is the correct syntax for this query?
var l=db.Fetch<article>("SELECT * FROM articles WHERE title LIKE '%#0%'", 'something');
Or should I use CHARINDEX?
May be
var l=db.Fetch<article>("SELECT * FROM articles WHERE title LIKE #0", "%something%");
I haven't tried this, but I think it is worth trying:
var l=db.Fetch<article>("SELECT * FROM articles WHERE title LIKE #0", "%" + "something" + "%");
If you have done your mappings (wich the T4 will do for you) then you could infact do it like so:
var l=db.Fetch<article>("WHERE title LIKE #0", "%something%");
Saves some typing :)
Can try like this also
var l=db.Fetch<article>("WHERE title LIKE #0", "%" + "something" + "%");
No need to write Select * From article, when you want to get all the fields. You are better off to use string.format to include the wildcards
var l=db.Fetch<article>("WHERE title LIKE #0", string.Format("%{0}%", yourVariable));
Articulo articulo = new Articulo();
articulo = db.SingleOrDefault<Articulo>("SELECT TOP (1) * FROM [Articulos] WHERE [CodigoEmpresa] = #0 and [CodigoArticulo] LIKE #1 ", CodigoEmpresa, codigoArticulo + "%");

how to use like query in drupal

How to write SQL LIKE Query in drupal ,
SELECT title FROM { node } WHERE type='%s'
i want to add the LIKE CONDITION IN THAT
SELECT title FROM { node } WHERE type='%s' AND LIKE '%S%'
i think i writtern wrong like query formnat, can rewrite and tell me,
Just use % to escape.
$result = db_query('SELECT title FROM {node} WHERE type = "%s" AND title LIKE "%%%s%%"', 'type', 'title');
while ($row = db_fetch_object($result)) {
// do stuff with the data
}
Node type does not need escaping.
And here is an example with how to use LIKE in a dynamic query (Drupal 7 Only):
$query = db_select('node', 'n')
->fields('n', array('title'))
->condition('type', 'my_type')
->condition('title', '%' . db_like(search_string) . '%', 'LIKE');
$result = $query->execute()->fetchCol();
db_like() is used to escapes characters that work as wildcard characters in a LIKE pattern.
drupal_query replace %% to % and %s to value string
so your code will be
$sql = "SELECT title FROM node WHERE type='%%%s' AND title LIKE '%%%S%%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
OK, so you want the LIKE operator to refer to the title column. Use this query:
$sql = "SELECT title FROM node WHERE type='%s' AND title LIKE '%S%'";
$type = "type to use in query";
$title = "title to use in query";
$result = db_result(db_query($sql, $type, $title));
This is because the LIKE operator requires a column name to be specified. Otherwise, your database doesn't have any idea what value you want to perform the comparison on. See here.