Note: Microsoft Books online is a default reference of all articles but examples and explanations prepared by Ritesh Shah, founder of http://www.SQLHub.com
One of the readers was using windows authentication in SQL connection string. When he tries to access database from connection string from Windows Application, it was working but when he tries to access same database with same connection string, it was throwing above error.
Main reason behind this error is permission issue. Now, question pops up in your mind, if that is a connection issue than why it was allowing same connection string in Windows application? Simple logical reason is that, Windows application uses local system account to connect with database when connection string built for Windows Authentication and ASP.NET uses ASPNET user of the web-server to connect with database. If your ASPNET user don’t have permission to access database, you will greeted with error
“Cannot open database ‘databasename’ requested by the login. The login failed for user ‘Machine-name/ASPNET’”.
So, now you know this is a permission issue, as soon as you will grant access to your db to ASPNET user, you will be ok but what, if you don’t have SQL Server client tool? It is quite possible if you are having SQL Express edition.
First let us see the command which will helpful to give permission to ASPNET user.
EXEC sp_grantlogin ‘Machine-name\ASPNET’
USE ADVENTUREWORKS–(YOUR DATABASE NAME)
EXEC sp_grantdbaccess ‘Machine-name\ASPNET’
EXEC sp_addrolemember ‘db_owner’, ‘Machine-name\ASPNET’
Run above script and you are done but what if you don’t have SQL Server client tool? You have to use OSQL utility from DOS prompt to run above command.
After getting DOS screen, follow below given command.
Note: “Ritesh” is my webserver name where ASPNET user resides. “.” in OSQL command represent my databse server you can give your SQL server’s IP or Name there, like: ‘Localhost\SQLExpress’
C:\Documents and Settings\Ritesh>cd\
C:\>osql -S . -E
1> sp_grantlogin ‘Ritesh\ASPNET’
1> use adventureworks
1> sp_grantdbaccess ‘Ritesh\ASPNET’
1> SP_addrolemember ‘db_owner’,’Ritesh\aspnet’
So, here with you will solve your error with above command along with OSQL utility which is good utility itself.
Reference: Ritesh Shah
Certificates in EE
MASTER SQL Server Apr 13, 2009
MASTER SQL Server 2005 Apr 22, 2009
GURU SQL Server Apr 26, 2009
Answer History in EE
1 Question Answered on Mar 26, 2009
50 Question Answered on APR 09, 2009
100 Question Answered on APR 19, 2009
150 Question Answered on APR 25, 2009
List is growing on and on
Moreover, I have entered in HALL of Fame for the year (12th), month (1st) and week(1st) in my very first month for SQL Server zone and in Month and Week for SQL server 2005 zone, looking forward to hold this position and enter in over all zone Hall of Fame very soon.