Solved

Avoiding "The server principal ... is not able to access the database ... under the current security context" runtime on 'USE [db]', how?

Posted on 2013-05-16
1
336 Views
Last Modified: 2013-05-17
In my code, I gather all database names and tables from a database server. However, there are cases where my User ID does not have the permission to "USE [database]". It would be too late because I will get an exception and some do not favor code that use exception handlers.

Here is the runtime error again:
"The server principal ... is not able to access the database ... under the current security context" ...

Is there an SQL query that I could use before issuing "USE [database]" that determines whether or not I could really "USE [database]" without getting the runtime error above?
0
Comment
Question by:rodqxo
1 Comment
 
LVL 16

Accepted Solution

by:
Surendra Nath earned 500 total points
ID: 39172456
the below one should help you

it will return 1 if you have permissions,replace <db_name> with the database name you are going to use with USE directive
SELECT HAS_PERMS_BY_NAME('<db_name>', 'DATABASE', 'ANY');
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how the fundamental information of how to create a table.

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now