SQL Server login problem for a windows service on reboot


I have a service that has a dependency on SQL server express (2005). Every morning when I reboot my machine, I see that the service has not started. In the event viewer, I see the following error:

Service cannot be started. System.Data.SqlClient.SqlException: Cannot open database "MyDatabase" requested by the login. The login failed.

Login failed for user 'NT AUTHORITY\SYSTEM'.

at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)

at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)

at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)

at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)

at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString conn…

If I now restart the service, it works fine but not on when I first power up the machine.

Any clues why this is happening?


Best Solution

I think it may happen when your service is started before SQL Server Express. I recommend checking out one of these solutions below:

  • add more attempts to login to database with appropriate delay time
  • check if Sql Server is running before you try to login to your database