You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
using OPTION with a UDF in the FromSql Method #6649
When running a SQL Function via the FromSql Method I've been having issues with Recursion. Basically a have a function that runs recursively and works out Future Due Dates.
Sometimes this function has to run a recursion more than 100 times (the default) and I would like to apply the OPTION (MAXRECURSION 2000) statement to the end of the SQL allowing the Function to run up to a 1000 times. Unfortunately this gives me an exception saying OPTION is invalid
So running the following code works
query = query.FromSql("SELECT * FROM udfSomeFunction ({0})", DateTime.Now());
I played around with this, and it looks like it works fine when you are just executing a SQL query, but fails when you compose on it with LINQ.
usingMicrosoft.EntityFrameworkCore;usingSystem;usingSystem.Linq;namespaceFromSql{classProgram{staticvoidMain(string[]args){using(vardb=newBloggingContext()){db.Database.EnsureDeleted();db.Database.EnsureCreated();db.Database.ExecuteSqlCommand("CREATE FUNCTION [dbo].[SearchBlogs] (@term nvarchar(200)) RETURNS TABLE AS RETURN (SELECT * FROM dbo.Blogs WHERE Url LIKE '%' + @term + '%')");db.Blogs.Add(newBlog{Url="http://sample.com/blogs/fish"});db.Blogs.Add(newBlog{Url="http://sample.com/blogs/catfish"});db.Blogs.Add(newBlog{Url="http://sample.com/blogs/cats"});db.SaveChanges();varterm="cat";varblogs=db.Blogs.FromSql("SELECT * FROM dbo.SearchBlogs({0}) OPTION (MAXRECURSION 2000)",term).OrderBy(b =>b.BlogId).ToList();foreach(varbloginblogs){Console.WriteLine(blog.Url);}}}}publicclassBloggingContext:DbContext{publicDbSet<Blog>Blogs{get;set;}protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder){optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Repro;Trusted_Connection=True;");}}publicclassBlog{publicintBlogId{get;set;}publicstringUrl{get;set;}}}
Here is the generated SQL
exec sp_executesql N'SELECT [b].[BlogId], [b].[Url]FROM ( SELECT * FROM dbo.SearchBlogs(@p0) OPTION (MAXRECURSION 2000)) AS [b]ORDER BY [b].[BlogId]',N'@p0 nvarchar(4000)',@p0=N'cat'
Full exception details
System.Data.SqlClient.SqlException was unhandled
Class=15
ErrorCode=-2146232060
HResult=-2146232060
LineNumber=3
Message=Incorrect syntax near the keyword 'OPTION'.
Number=156
Procedure=""
Server=(localdb)\mssqllocaldb
Source=.Net SqlClient Data Provider
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean openConnection, Boolean closeConnection)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues, Boolean manageConnection)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.<_ShapedQuery>d__3`1.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.<_TrackEntities>d__15`2.MoveNext()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at FromSql.Program.Main(String[] args) in C:\Code\Demo-EFCore\StartingSourceCode\FromSql\Program.cs:line 23
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
My understanding is that (unlike table hints) query hints such as OPTION (MAXRECURSION n)
apply to the whole query and can only be placed at the end of the statement. So they are not really part of the SELECT statement, or at least they are not composable in the same way.
It sounds like there is a good opportunity for building a general query hint feature that can be used to flow provider specific hints into the SQL or an even much simpler ability to append arbitrary text as a query terminator.
In the meanwhile the work around is to write the whole query in SQL, e.g. for @rowanmiller's example above:
varblogs=db.Blogs.FromSql(@"SELECT [b].[BlogId], [b].[Url] FROM dbo.SearchBlogs({0}) AS [b] ORDER BY [b].[BlogId] OPTION (MAXRECURSION 2000)",term).ToList();
Activity
rowanmiller commentedon Oct 4, 2016
I played around with this, and it looks like it works fine when you are just executing a SQL query, but fails when you compose on it with LINQ.
Here is the generated SQL
Full exception details
divega commentedon Oct 4, 2016
My understanding is that (unlike table hints) query hints such as
OPTION (MAXRECURSION n)apply to the whole query and can only be placed at the end of the statement. So they are not really part of the
SELECTstatement, or at least they are not composable in the same way.It sounds like there is a good opportunity for building a general query hint feature that can be used to flow provider specific hints into the SQL or an even much simpler ability to append arbitrary text as a query terminator.
In the meanwhile the work around is to write the whole query in SQL, e.g. for @rowanmiller's example above:
rowanmiller commentedon Oct 7, 2016
Opened #6717 to track the idea of being able to append SQL to the end of a query.