I am currently making a vb.net program that needs to check permissions on a table (if the table does not exsist, then the permission on the database, if the database does not exsist, then the permission to the sql server)
is there a way to check thouse permissions, and how?
i've been searching on google, but the result i got, was a 2 pages long sql script.
I would push responsibility of creating the database onto the end-user - and allow the user to specify that database; it may be valid for an installer to create the database, but again it should also accept one already created where the name has been supplied by the end user. You do not want to assume a database name as if the end-user already has a database created with that name, you will be in direct conflict with it.
That said, permissions are stored in sys.database_permissions
which outline a user's permissions in the database this is queried from and sys.server_permissions
to find out if they have the ability to create a database.
Helpfully though SQL Server have a function that wraps up querying permissions - the HAS_PERMS_BY_NAME
function comes in handy here, for example:
SELECT HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE TABLE')
...will look to see if the current user has the ability to 'CREATE TABLE' in the named database, whilst
SELECT HAS_PERMS_BY_NAME(null, null, 'CREATE ANY DATABASE')
...will tell you if the current user can create databases. The names of the permissions are those that you'd pass through to GRANT
. Consult the docs for more information and examples.