Question

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?

  • how do i check the permissions on the table "testdb.testtable" for the user "testuser"
  • how do i check the permissions on the database "testdb" for the user "testuser"
  • how do i check the permissions on the server for user "testuser"

i've been searching on google, but the result i got, was a 2 pages long sql script.

Was it helpful?

Solution

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.

OTHER TIPS

I also was able to assemble another SQL Query.. however this will return an error, if the user does not have access to the database.

SELECT pe.*,object_name(pe.major_id), pr1.name as Grantee, pr2.name as Grantor, pr1.create_date,pr1.default_schema_name  from sys.database_permissions as pe
join sys.database_principals as pr1 on pe.grantee_principal_id = pr1.principal_id 
join sys.database_principals as pr2 on pe.grantor_principal_id = pr2.principal_id
where pr1.name = CURRENT_USER 
go

by adding "use ReplaceWithNameOfDatabase"

the query will ask up against that database.

i've never really worked with MSSQL before, only MYSQL, and it seems there is alot of big diffrences in how userlogin data is stored.

i found this SQL Server: Permissions on table worked for me, with a little modification

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top