title: Why does the stored procedure run slow from code, but fast from SSMS?
body: <p>I am running a stored procedure from my web app, using Dapper. I ran the same stored procedure from SSMS first, to make sure all is well. It ran in 1-5 seconds from SSMS. </p>
  
  <p>Then I copied/pasted my script into my app to be run through Dapper. When I ran my app and step debugged my code, the stored procedure ran for over 2 minutes and timed out. It's the same exact code. What could be causing the discrepancy?</p>
  
  <p>Here is my code I am running from SSMS:</p>
  
  <pre><code>DECLARE @RC int
  DECLARE @ownerId varchar(50)
  DECLARE @type varchar(50)
  DECLARE @dateFrom datetime
  DECLARE @dateTo datetime
  DECLARE @offset int
  DECLARE @perPage int
  
  SET @ownerId = '990042064' 
  SET @type = 'voice' 
  SET @dateFrom = '2018-05-16 00:00:00.000'  --'YYYY-MM-DD hh:mm:ss[.nnn]' 
  SET @dateTo = '2018-08-14 23:59:59.000'  --'YYYY-MM-DD hh:mm:ss[.nnn]' 
  SET @offset = 0 
  SET @perPage = 50
  
  EXECUTE @RC = dbo.IndexSearch @ownerId
                               ,@type
                               ,@dateFrom
                               ,@dateTo
                               ,@offset
                               ,@perPage
  GO
  </code></pre>
  
  <p>And here is the code running from my app:</p>
  
  <pre><code>using (IDbConnection db = new SqlConnection(ConnectionStringHelper.ConnectionString))
  {
      dbRecs = db.Query&lt;IndexRec&gt;(@"
      DECLARE @RC int
      DECLARE @ownerId varchar(50)
      DECLARE @type varchar(50)
      DECLARE @dateFrom datetime
      DECLARE @dateTo datetime
      DECLARE @offset int
      DECLARE @perPage int
  
      SET @ownerId = '990042064'
      SET @type = 'voice'
      SET @dateFrom = '2018-05-16 00:00:00.000'--'YYYY-MM-DD hh:mm:ss[.nnn]'
      SET @dateTo = '2018-08-14 23:59:59.000'--'YYYY-MM-DD hh:mm:ss[.nnn]'
      SET @offset = 0
      SET @perPage = 50
  
      EXECUTE @RC = dbo.IndexSearch @ownerId
                                   , @type
                                   , @dateFrom
                                   , @dateTo
                                   , @offset
                                   , @perPage
      ", commandTimeout: 120);
  }
  </code></pre>
  
  <p>I've even tried running SSMS on a couple different machines, and I always get it in 1-5 seconds. And I have run the same query several times from the app, and it always times out. </p>
  
  <p>Could there be anything in the script itself that causes the execution plan to be different? I am also using the same login from SSMS and my app.</p>