Tutorial :LINQ's FirstOrDefault in SQL script?



Question:

What is the SQL language keyword for the LINQ-to-SQL FirstOrDefault or SingleOrDefault?

Is it TOP(1)?

EXAMPLE:

SELECT TOP(1) @ItemCode = ItemCode FROM VendorItem WHERE VendorId = @VendorId   

There can't be more than 1 results anyway since there is a Unique Key constranint, do I have to spell out the TOP(1) or whatever it is?

Note: I don't need LINQ answers, my question is how to write the sql script.


Solution:1

If there is a unique key constraint you do not need to add anything to have the FirstOrDefault behavior. For other queries you can add

LIMIT 1

to the end of your SQL query. This will just give you the first answer which matches your constraints.

Edit after comment: To get it as a scalar in .NET you can use the SQLCommand.ExecuteScalar method.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »