How to call a UDF in a linq to sql query? - linq-to-sql

How would the following sql statement translate to a linq query?
select ID,
Price,
dbo.fGetText(DescriptionID, defaultLanguage, currentUserLanguage)
from Products
The UDF fGetText is quite substantial and used throughout the code base, so it needs to be encapsulated (as a UDF or otherwise, perhaps a Linq Expression).
Extra round trips to the database server are not a option. There should only be one query, retrieving 3 fields.
Many thanks in advance for your help. It is greatly appreciated.

Here is the MSDN article:
How to: Call User-Defined Functions Inline (LINQ to SQL)
A note from the same page:
Although you can call user-defined
functions inline, functions that are
included in a query whose execution is
deferred are not executed until the
query is executed. For more
information, see Introduction to LINQ
Queries.
When you call the same function
outside a query, LINQ to SQL creates a
simple query from the method call
expression
Also, take a look at this 13 min screencast.

You can add UDF's to a LINQ to SQL DBML file just like you add tables and sprocs.
They then become executable methods on the DataContext.
Google has lots of articles, like this.

Related

Converting Foxpro program to MySQL stored procedure

I am in a process on converting a legacy system to web app using Ruby on Rails and MySQL.
There are few places that I'm stuck at while converting the data layer to MySQL procedures.
Giving a scenario below;
FUNCTION first_function
SELE Table1
REPL Table1.SmaCode WITH SMA(code,HcPc,FromDate)
ENDFUNC
FUNCTION SMA
... Lot of conditions ...
Lookup(param1,param2) * Parameters are based on the conditions above
.. Lot more conditions ....
ENDFUNC
FUNCTION Lookup
temp = Output of select on Check table
return temp
ENDFUNC
Here SMA is another function which has so many conditions and it also calls another function Lookup. In Lookup function it query a table named Checks, the parameter to Lookup is based on the SMA.
Please see the pastebin of the source code in disucssion, if you need more insight. http://pastebin.com/raw/Hvx3b8zN
How can I go and convert this kind of functions to MySQL procedures?
Edit:
I'm looking for insights on this from people who've already done these types of conversions, from procedure oriented languages to set based stored procedures to be exact.
The commentators are all right and I upticked them all. You have to actually write the code but it's not too hard once you get going.
The first thing I do is to examine my code and rewrite all the straightforward things like DELETE FOR .... into DELETE WHERE...
Then I look at my loops and think about how I can treat that data as a set. A lot of times, SCANs can be written as a regular query when you use appropriate JOIN conditions and WHERE conditions. There are a lot of query tools like CASE and subqueries that let you get a lot done with very little code. MySQL allows temporary tables and that can come in very useful. Lookups can often be done with subqueries.
On occasions, I have to use FETCH and WHILE loops but I avoid that as much as possible because it is slow and SQL is set based.
Just get started on the easy stuff and you'll get the hang of it :)

Create Function Teradata

I want to create a small function (or like) which will take parameters and return result of excuting teradata sql statement. Purpose of this is to convert repeated using SQL into function which can be used into SELECT statement.
Please point me into right direction. Create Function in teradata requires C/C++ compilation which is too much effort after looking at use of required function.
Passing parameters to SQL can be done using a CREATE MACRO, but those can't be used in a SELECT.
SQL-UDFs are limited to simple scalar functions in Teradata, i.e. no SELECTs, etc.
If you need a more complex function (table or [window] aggregate) you must write it in C or Java.

Can I obfuscate the SQL code in MySQL?

I'm trying to find some way to obfuscate SQL code in MySQL.
In the Oracle databases exists the "wrap" funcionality, but I didn't found some similar. Some ideas?
The final goal is that the client has some difficuties to understand the code.
I think MySQL do not have the ability to obfuscate the code. You can encapsulate the whole SQL query code by creating a STORED PROCEDURE, although not encapsulated but at least your whole SQL query is not shown when used inside your code (PHP, .Net, and the like...).
MySQL does not have any obfuscation abilities - you could write some code that would be confusing to read by having some other table with defined values that you could use IF statements against to make your code difficult to read...
SELECT co1, co2, IF(3 > 18, co3, '') AS co3 FROM table INNER JOIN...
etc... or using COUNTs as parameters in conditional statements is as best as you're going to get (obviously performance may become an issue depending on how "obfuscated").

Inline table-valued function vs Stored Procedure (SQL Server)

I'm a bit confused about what is better to use in the following case:
I have a quite complex query that is used for reporting purposes. A simplified version looks like
SELECT [type], COUNT(*) as total_num, COUNT(DISTINCT user_id) as uq_user_num
FROM table1
INNER JOIN table2 ON (...)
...
WHERE table3.last_action_date BETWEEN :start_date AND :end_date
GROUP BY [type]
I can create an inline function or a stored procedure that takes start_date and end_parameters and executes this query.
I incline to function because this task does not involve any data modification or complex logic. Also, I may want to use the result in APPLY later (it's not really important at the moment).
Does it make sense to use function, not procedure? Is it any difference from performance point of view (execution plan caching, etc) ?
Thank you.
Using a multi-statement table valued function is similar to using a proc from plan caching and cached plan reuse perspective.. Using an inline table valued function is similar to using a view from the plan cache and plan reuse perspective(reuse only happen is exact same statement is used. ie same parameters).
Considering the same you should use a multi-statement table valued function.
You may want to consider using a View too. A view is efficient if the results do no change given the parameters provided, which is what you have here. In this case, the results will not change if you make two calls with the same start and end date.
However, two of the main differences between a stored proc and a function are that you cannot call updates/ inserts from a function and you cannot call a stored proc as part of a select statement, but you can with a function.
See this thread for more info:
Function vs. Stored Procedure in SQL Server

Whats the Efficient way to get data from db using LINQ To SQL or LINQ To Entities?

When you run Linq to Sql or Linq to Entites to get a list of records it runs query to select all fields from a table. Is it an efficient solution. Lets say: I run this LINQ
dim lstCustomers = from c in db.Customers select c
it run query to get all fields from a table whether i need all fields or not. I am using asp.net with MVC so should i write this query in view (where i only need CustomerID and name)
dim lstCustomers = from c in db.Customers _
select new Customer with { c.CustomerID, c.Name }
If i have to use 2nd query then whats the advantage of LINQ and Entity Framework. This thing i can do with SQL query (with different syntax)
Anyone can help?
First of all, LINQ queries are evaluated lazily. That means that single line doesn't do anything but itself, so I assume you actually iterate the results with For Each.
The answer to your first question is yes, all fields are retrieved from the database with the first statement.
Yes, but in order to use SQL directly, you'll have to manually create entity classes, manually retrieve data using SqlDataReader or something to achieve the level of abstraction LINQ provides in that line. That's lots of more work on your behalf. With LINQ to SQL, you don't even need to explicitly write code to open a connection to database.
actuly linq have different sets of advantages over writing normal writing sql queries:
if you wrote sql queries then overloaded steps:
1. you need a sql connection class
2. you need a sql command or sqldataadapter.
3.then you need a container like datatable and dataset.
so while using linq you dont need all those steps. just write the queries as you wrote above.
also incase you wrote something incorrect in your sqlquery then there is no compile time error. error only generates when you execute the query during runtime.
but unlike sql queries, linq provides you the compile time error.
also linq is best of strongly type collections.