title: Arithmetic overflow error converting expression to data type nvarchar Error 8115 until SQL Agent runs in the morning
body: <p>I have an SQL Agent job that runs every 15 minutes from 9:15am to 6pm. </p>
  
  <pre><code>DECLARE @db_name varchar(100) 
  DECLARE c_db_names CURSOR FOR
  SELECT name 
  FROM sys.databases
  WHERE name NOT IN
  ('VARIOUS DATABASES HERE')
  TRUNCATE TABLE DBDATA.dbo.DATA
  OPEN c_db_names
  
  FETCH c_db_names INTO @db_name
  
  WHILE @@Fetch_Status = 0
  BEGIN
    EXEC('
      INSERT INTO DBDATA.dbo.DATA
      SELECT 
        ''' + @db_name + '''
        ,COUNT(*)
        ,MIN(datereq)
      FROM ' + @db_name + '.dbo.TABLE
    ' + 'where lqdone = 0')
    FETCH c_db_names INTO @db_name
  END
  
  CLOSE c_db_names
  DEALLOCATE c_db_names
  </code></pre>
  
  <p>If there are any results I email them to myself. For some unknown reason to me, for the past two or three weeks I'm unable to run that query before 9:15am in the morning when the SQL Agent starts the job and fails with the error message as per the subject. Every next attempt works just fine, it only fails at 9:15am and earlier if I try to run it manually. Really puzzled and not sure what is happening here.</p>
  
  <p>The datereq field is datetime, db_name is nchar. It fails on the 11th database it checks but I've checked the table and its exactly the same as the other ones.</p>
  
  <p>Any ideas? :)</p>