Skip to content

using OPTION with a UDF in the FromSql Method #6649

Closed as not planned
Closed as not planned

Description

@NeilWBruce

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());

but when I add the option statement to it

query = query.FromSql("SELECT * FROM udfSomeFunction ({0}) OPTION (MAXRECURSION 2000)", DateTime.Now());

I get an exception

I'm running the 1.0.1 Version of Entity Framework Core.

Activity

  1. rowanmiller commented on Oct 4, 2016

    @rowanmiller
    Contributor

    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.

    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Linq;
    
    namespace FromSql
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new BloggingContext())
                {
                    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(new Blog { Url = "http://sample.com/blogs/fish" });
                    db.Blogs.Add(new Blog { Url = "http://sample.com/blogs/catfish" });
                    db.Blogs.Add(new Blog { Url = "http://sample.com/blogs/cats" });
                    db.SaveChanges();
    
                    var term = "cat";
    
                    var blogs = db.Blogs
                        .FromSql("SELECT * FROM dbo.SearchBlogs({0}) OPTION (MAXRECURSION 2000)", term)
                        .OrderBy(b => b.BlogId)
                        .ToList();
    
                    foreach (var blog in blogs)
                    {
                        Console.WriteLine(blog.Url);
                    }
                }
            }
        }
    
        public class BloggingContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Repro;Trusted_Connection=True;");
            }
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { 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: 
    
  2. divega commented on Oct 4, 2016

    @divega
    Contributor

    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:

    var blogs = db.Blogs
        .FromSql(
            @"SELECT [b].[BlogId], [b].[Url]
            FROM dbo.SearchBlogs({0}) AS [b]
            ORDER BY [b].[BlogId] OPTION (MAXRECURSION 2000)",
            term)
        .ToList();
  3. rowanmiller commented on Oct 7, 2016

    @rowanmiller
    Contributor

    Opened #6717 to track the idea of being able to append SQL to the end of a query.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions