How can we use LIKE operator in WHEREusing Simple.Data for SQL Server in ASP.Net C#
I need to run this SQL Query
SELECT MAX(regid) FROM reg_course WHERE(regid LIKE '%2013%')
Finally I achieved this task by aliasing the max(regid) column and querying in this fashion.
var cid=db.course_test.All()
.Select(db.course_test.regid.Max().As("maxcourseid"))
.Where(db.course_test.regid.Like(string.Concat("%",DateTime.Now.Year,"%")))
.FirstOrDefault();
Note
cid=db.course_test.All()
.Select(db.course_test.regid.Max().As("maxcourseid"))
.Where(db.course_test.regid.Like(string.Concat("%",DateTime.Now.Year,"%")))
returns the type Simple.Data.SqlQuery
Using FirstOrDefault returns Top result. If you don't want you can iterate in collection without using FirstOrDefault
Any other Better way Suggestions??
Related
I am working on .NET CORE 2.0 application and part of that I am require sort GUID in descending order. I have list of GUID in List pass to another method where this collection is sorted in descending order but I have found result is different then use IQueryable Linq as select(x=>x.id).OrderByDescending(x=>x) also comparing with SQL Server, the second option seems correct.
I need List sort in descending order output as same result as IQueryable Linq as select(x=>x.id).OrderByDescending(x=>x)
List<Guid> sortedList =
C95F4897-35D8-409D-BF0E-B0D6E1BCAC55
D867FD57-F728-46E9-BFF0-F168BAC674C4
F05BCAA7-600E-406F-B9F3-7CD839FFC98B
383525C6-F158-431C-A6A5-B42FF3CBF5AE
I have also tried following code but not getting correct result
var s1 = sortedList.OrderByDescending(i => i);
sortedList.Sort();
sortedList.Reverse();
data without sort
data IQueryable sort in LINQ (this is result I am after but from collection.sort
data sort from collection
When you call .OrderByDescending on a list, you are calling Enumerable.OrderByDescending. Conversely, when you are calling .OrderByDescending on a linq query, you are calling Queryable.OrderByDescending.
The difference (the difference that matters here) is the enumerable method uses the default comparer (in this case of datatype GUID), while the queryable method is converted to a sql statement which is executed on the database, hence using the SQL comparer (of uniqueidentifier). The GUID comparer uses all 16 bytes equally, while in SQL the last 6 bytes are the most significant (Source1, Source2(old, but still valid)).
You say you desire the result of the queryable method, while using the enumerable method (in essence). You can achieve this by using the System.Data.SqlTypes.SqlGuid datatype instead of system.Guid. You can simply cast your Guid's to SqlGuid's. Alternatively, and probably a much cleaner solution, you can create your own comparer using SqlGuid.CompareTo method, and use that in the order by: OrderByDescending(x => x, new MyComparer()) .
I've been trying to figure out which one to use when, and if I should even use both.
Been looking at Laravel docs and they have both in there. From what I can make out of it, DB::insert() provides more "tailored" query than DB::table()->insert() does.
Would anyone be able to clarify what exactly the difference is in the two when it comes to how and when to use which?
DB::insert() for raw sql queries. Example:
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
DB::table()->insert() for query builder. Example:
DB::table('users')->insert(
['email' => 'john#example.com', 'votes' => 0]
);
Query builder compiles conditions to raw sql query, but I am using it because it is much more convenient.
You always try to use query builder as much as possible, it prevents SQL injection.
The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings
Query Builder also helps with special chars such as ', " in values. For raw statement, you need to take care of the special chars yourself.
public function addsubEmployee(Request $reqest){
Sub_employee::create([
"se_name"=> $reqest->se_name,
]);
return redirect()->route("subEmployee");
}
I am trying to start using EF6 for a project. My database is already filled with millions of records.
I can't find right explanation how does EF send T-SQL to SQL Server? I am afraid that I am going to download bunch of data to user for no reason.
In code below I have found three way to get my data to List<> but I am not sure which is right way to do WHERE clause at SQL.
I do not want to fill client with millions of record and to query (filter) that data at client.
using (rgtBaza baza = new rgtBaza())
{
var t = baza.Database.SqlQuery<CJE_DOC>("select * from cje_doc where datum between #od and #do",new SqlParameter("od", this.dateTimePickerOD.Value.Date ) ,new SqlParameter("do", this.dateTimePickerOD.Value.Date)).ToList();
var t = baza.CJE_DOC.Where(s => s.DATUM.Value >= this.dateTimePickerOD.Value.Date && s.DATUM.Value <= this.dateTimePickerDO.Value.Date).ToList();
var query = from b in baza.CJE_DOC
where b.DATUM >= this.dateTimePickerOD.Value.Date && b.DATUM.Value <= this.dateTimePickerDO.Value.Date
select b;
var t = query.ToList();
this.dataGridViewCJENICI.DataSource = t;
}
In all 3 cases, the filtering will happen on the database side, the filtering (or WHERE clause) will not take place on the client side.
If you want to verify that this is true, especially for your last 2 options, add some logging so that you can see the generated SQL:
baza.Database.Log = s => Console.WriteLine(s);
In this case, since you are using EF already, choose the 2nd or 3rd options, they are both equivalent with different syntax. Pick your favorite syntax.
In all of those examples, EF6 will generate a SQL query including the where clause - it won't perform the where clause on the client.
It won't actually retrieve any data from the database until you iterate through the results, which in the examples above, is when you call .ToList().
EF6 would only run the filter on the client if you called something like:
baza.CJE_DOC.ToList().Where(x => x.Field == value)
In this instance, it would retrieve the entire table when you called ToList(), and then use a client-side Linq query to filter the results in the where clause.
Any of the 3 will run the query on the SQL Server.
EF relies on LINQ's deferred execution model to build up an expression tree. Once you take an action that causes the expression to be enumerated (e.g. calling ToList(), ToArray(), or any of the other To*() methods), it will convert the expression tree to SQL, send the query to the server, and then start returning the results.
One of the side effects of this is that when using the query or lambda syntax, expressions that EF does not understand how to convert to SQL will cause an exception.
If you absolutely need to use some code that EF can't handle, you can break your code into multiple segments -- filtering things down as far as possible via code that can be converted to SQL, using the AsEnumerable() method to "close off" the EF expression, and doing your remaining filtering or transformations using Linq to Objects.
I've got some XML Data in a SQL Server Table in an XML Column as follows:
<AffordabilityResults>
<matchlevel xmlns="urn:callcredit.co.uk/soap:affordabilityapi2">IndividualMatch</matchlevel>
<searchdate xmlns="urn:callcredit.co.uk/soap:affordabilityapi2">2013-07-29T11:20:53</searchdate>
<searchid xmlns="urn:callcredit.co.uk/soap:affordabilityapi2">{E40603B5-B59C-4A6A-92AB-98DE83DB46E7}</searchid>
<calculatedgrossannual xmlns="urn:callcredit.co.uk/soap:affordabilityapi2">13503</calculatedgrossannual>
<debtstress xmlns="urn:callcredit.co.uk/soap:affordabilityapi2">
<incomedebtratio>
<totpaynetincome>0.02</totpaynetincome>
<totamtunsecured>0.53</totamtunsecured>
<totamtincsec>0.53</totamtincsec>
</incomedebtratio>
</debtstress>
</AffordabilityResults>
You'll note that some of the elements have an xmlns attribute and some don't...
I need to write queries to return the data - and more importantly show a business analyst how to write her own queries to get the data she needs so I want it to be as simple as possible.
I can query the data easily using the WITH XMLNAMESPACES element as follows:
WITH XMLNAMESPACES (N'urn:callcredit.co.uk/soap:affordabilityapi2' as x )
SELECT
ResponseXDoc.value('(/AffordabilityResults/x:matchlevel)[1]','varchar(max)' ) AS MatchLevel
, ResponseXDoc.value('(/AffordabilityResults/x:debtstress/x:incomedebtratio/x:totamtunsecured)[1]','nvarchar(max)' ) AS UnsecuredDebt
FROM [NewBusiness].[dbo].[t_TacResults]
But adding the x: part to the query makes it look overly complicated, and I want to keep it simple for the business analyst.
I tried adding:
WITH XMLNAMESPACES (DEFAULT 'urn:callcredit.co.uk/soap:affordabilityapi2' )
and removing the x: from the XQuery - but this returns null (possibly because of the lack of the xmlns on the root element?)
Is there any way I can simplify these queries either with or without the default namespace?
If namespaces are not important in your use case, you could use the namespace wildcard selector *:, which both selects nodes without and with arbitrary namespaces.
An example query could be
(/*:AffordabilityResults/*:matchlevel)[1]
The business analyst will still have to add the selector in front of every node test, but it's the same "prefix" all the time and the only error to be expected is forgetting to use it somewhere.
I want to write a query that does something like this SQL query:
SELECT name FROM contacts WHERE blah blah
I know I can do something like this:
for contact in Contacts.gql(WHERE_CLAUSE, args).fetch(1000):
print contact.name
but isn't there a way to get name directly from a query without having to loop on the results? would it provide any advantage in performance?
Nope. Can't be done.
A GQL query returns zero or more entities or Keys of the requested
kind. Every GQL query always begins with either SELECT * or SELECT
key. (A GQL query cannot perform a SQL-like "join" query.)
http://code.google.com/appengine/docs/python/datastore/gqlreference.html
But you can create a simple wrapper to do it for you. Something like:
def get_all_of_field(model, field):
for x in model.all():
yield getattr(x, field)
names = get_all_of_field(Contact, 'name')
Performance can't be improved that way as the entire "line" is read by the API no matter what. Either you read the entire "line" or just its key.
You can do this now using Projection queries. For db, see the documentation here:
https://developers.google.com/appengine/docs/python/datastore/projectionqueries
For ndb, see the documentation here:
https://developers.google.com/appengine/docs/python/ndb/queries#projection