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
332 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

Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

Join & Write a Comment

Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
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 information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

706 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

15 Experts available now in Live!

Get 1:1 Help Now