View Definition Permissions in SQL Server

View Definition Permissions in SQL Server

View Definition Permissions in SQL Server

SQLShack

SQL Server training Español

View Definition Permissions in SQL Server

July 9, 2019 by Rajendra Gupta We have various database objects such as view, stored procedures, triggers, functions and indexes in a relational database. Many times, we want to view definitions for these objects. We can use either SSMS graphical way or t-SQL to generate scripts. For example, we want to view the definition of a SQL view [HumanResources].[vEmployee]. Let’s explore both ways to generate scripts.

Different methods to view the definition of objects

SSMS Script Wizard

Expand the database and go to Views. Right-click on a particular view for which we want to generate script and click on Script View as ->Create To. We can get the script in the following ways. In the new query window Get the script in the .SQL file Copy the script in the clipboard Get script in a SQL Agent job

Generate Script Wizard

We can use Generate Script Wizard in SSMS as well to generate script. Right-click on a database and go to Tasks -> Generate Scripts. In the generate script wizard, select the specific database object and click on Next. You can complete the wizard to get the script.

Using t-SQL

We can use t-SQL queries as well to get the script of the objects. You can use the following t-SQL methods to get definitions for an object. Get scripts using the Information_Schama.Views: Execute the following query in the source database and specify the object name in the where clause 1234 SELECT TABLE_NAME as ViewName,VIEW_DEFINITION as ViewDefinitionFROM INFORMATION_SCHEMA.Viewswhere TABLE_NAME='vEmployee' Sp_helptext system procedure: You can use sp_helptext system procedure as well to get the script. You need to specify the object name along with the schema if it is other than dbo. 1 EXEC sp_helptext '[HumanResources].[vEmployee]' object_definition function We can use an object_definition function as well to generate a script for the object. In the following query, we use the object_definition function for a view vEmployee in the AdventureWorks2017 database 1 SELECT object_definition (OBJECT_ID(N'[HumanResources].[vEmployee]'))

Permissions required to generate objects script

It is an essential aspect for any DBA to control the user permissions for accessing the objects. Many times users require additional rights on a database to perform their duty. By default, users with public role do not have permissions to view the definition of an object. It is useful for the developers to get the object definitions so that they can execute this in a non-production environment. We also do not want to give privileged permissions to users, especially in the production environment. Let’s create a new database user and provide a public role in the AdventureWorks2014 database. Connect to SQL Server using the login credentials having Public role permission. Execute the query to get the view definition of an object. The command sp_helptext gives an error message that an object does not exist in the database. If we try to get the script using INFORMATION_SCHEMA.Views, it does not give any error message; however, it does not return any row. You cannot use the SSMS as well because it does not show the objects for the public role access. We can use View Definition permission in SQL Server to allow users to view the object definitions. We can either provide this access to a public role or an individual user. If we want to provide view object definition rights to all users with public role, execute the following query. This query gives rights for all online databases in the instance 123 USE master GO GRANT VIEW ANY DEFINITION TO PUBLIC If we want to provide view object definition rights to a specific user with the public role on all databases, execute the following query 1234 USE master GO GRANT VIEW ANY DEFINITION TO Rajendra If we want to give object definition for all users with a public role in a specific database, execute the following query 123 USE AdventureWorks2017GO GRANT VIEW ANY DEFINITION TO PUBLIC If we want to provide view object definition rights to a specific user with a public role on a specific database, execute the following query 123 USE AdventureWorks2017GO GRANT VIEW ANY DEFINITION TO Rajendra To grant View Definition rights to a specific user and an object for a particular database 1 GRANT VIEW DEFINITION on [HumanResources].[vEmployee] TO Rajendra Let’s provide access to a specific user (Rajendra) on a specific object ( [HumanResources].[vEmployee]) and verify the permissions to view the definition of an object. 1 EXEC sp_helptext '[HumanResources].[vEmployee]' You can try other methods to view object definitions specified in the previous section. You can refresh connection in SSMS as well to view all objects after assigning the View Definition permissions. We can keep track of the permissions using the sp_helprotect command. 123 USE AdventureWorks2017GO sp_helprotect In the screenshot below, you can observe the following: Object: vEmployee Owner( Schema) : HumanResources Grantee ( User): Rajendra Grantor ( permission Grantor): dbo Permission: Grant Action( rights): View Definition

Revoke View Definitions permission

We learned to Grant the View definition permissions to a user, role or object in SQL Server in the previous section. It is also an important aspect to know how to revoke these View Definitions permissions. Many times, we might want to give temporary access to a user and revoke it later. We can revoke the permissions to the user across all databases with the Revoke View Any Definition command. Script to revoke View Definition permissions for all users with a public role 123 USE master GO REVOKE VIEW ANY DEFINITION TO PUBLIC Script to revoke permissions for a specific user with a public role on all databases 123 USE master GO REVOKE VIEW ANY DEFINITION TO Rajendra --Specify the user name Script to revoke permissions for all users with a public role on a specific databases 123 USE AdventureWorks2017 --Specify the database nameGO REVOKE VIEW ANY DEFINITION TO PUBLIC Script to revoke permissions for a specific user with a public role on a specific databases 123 USE AdventureWorks2017GO REVOKE VIEW ANY DEFINITION TO Rajendra Script to revoke permissions for a specific user and an object for a particular database 123 USE AdventureWorks2017GO REVOKE VIEW DEFINITION on [HumanResources].[vEmployee] TO Rajendra

Conclusion

In this article, we explored Grant and Revoke view definition permissions in SQL Server to view definitions for an object. It provides you with the necessary information to manage the permissions for object definitions. If you have any comments or questions, feel free to leave them in the comments below. Author Recent Posts Rajendra GuptaHi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book "DP-300 Administering Relational Database on Microsoft Azure". I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at [email protected]

View all posts by Rajendra Gupta Latest posts by Rajendra Gupta (see all) Copy data from AWS RDS SQL Server to Azure SQL Database - October 21, 2022 Rename on-premises SQL Server database and Azure SQL database - October 18, 2022 SQL Commands to check current Date and Time (Timestamp) in SQL Server - October 7, 2022

Related posts

Creating an automatic View to an In-line table function conversion stored procedure SQL Server deadlock definition and Overview Move or copy SQL Logins by assigning roles and permissions SQL View – A complete introduction and walk-through How to create a view in SQL Server 164,099 Views

Follow us

Popular

SQL Convert Date functions and formats SQL Variables: Basics and usage SQL PARTITION BY Clause overview Different ways to SQL delete duplicate rows from a SQL Table How to UPDATE from a SELECT statement in SQL Server SQL Server functions for converting a String to a Date SELECT INTO TEMP TABLE statement in SQL Server SQL WHILE loop with simple examples How to backup and restore MySQL databases using the mysqldump command CASE statement in SQL Overview of SQL RANK functions Understanding the SQL MERGE statement INSERT INTO SELECT statement overview and examples SQL multiple joins for beginners with examples Understanding the SQL Decimal data type DELETE CASCADE and UPDATE CASCADE in SQL Server foreign key SQL Not Equal Operator introduction and examples SQL CROSS JOIN with examples The Table Variable in SQL Server SQL Server table hints – WITH (NOLOCK) best practices

Trending

SQL Server Transaction Log Backup, Truncate and Shrink Operations Six different methods to copy tables between databases in SQL Server How to implement error handling in SQL Server Working with the SQL Server command line (sqlcmd) Methods to avoid the SQL divide by zero error Query optimization techniques in SQL Server: tips and tricks How to create and configure a linked server in SQL Server Management Studio SQL replace: How to replace ASCII special characters in SQL Server How to identify slow running queries in SQL Server SQL varchar data type deep dive How to implement array-like functionality in SQL Server All about locking in SQL Server SQL Server stored procedures for beginners Database table partitioning in SQL Server How to drop temp tables in SQL Server How to determine free space and file size for SQL Server databases Using PowerShell to split a string into an array KILL SPID command in SQL Server How to install SQL Server Express edition SQL Union overview, usage and examples

Solutions

Read a SQL Server transaction logSQL Server database auditing techniquesHow to recover SQL Server data from accidental UPDATE and DELETE operationsHow to quickly search for SQL database data and objectsSynchronize SQL Server databases in different remote sourcesRecover SQL data from a dropped table without backupsHow to restore specific table(s) from a SQL Server database backupRecover deleted SQL data from transaction logsHow to recover SQL Server data from accidental updates without backupsAutomatically compare and synchronize SQL Server dataOpen LDF file and view LDF file contentQuickly convert SQL code to language-specific client codeHow to recover a single table from a SQL Server database backupRecover data lost due to a TRUNCATE operation without backupsHow to recover SQL Server data from accidental DELETE, TRUNCATE and DROP operationsReverting your SQL Server database back to a specific point in timeHow to create SSIS package documentationMigrate a SQL Server database to a newer version of SQL ServerHow to restore a SQL Server database backup to an older version of SQL Server

Categories and tips

►Auditing and compliance (50) Auditing (40) Data classification (1) Data masking (9) Azure (295) Azure Data Studio (46) Backup and restore (108) ►Business Intelligence (482) Analysis Services (SSAS) (47) Biml (10) Data Mining (14) Data Quality Services (4) Data Tools (SSDT) (13) Data Warehouse (16) Excel (20) General (39) Integration Services (SSIS) (125) Master Data Services (6) OLAP cube (15) PowerBI (95) Reporting Services (SSRS) (67) Data science (21) ►Database design (233) Clustering (16) Common Table Expressions (CTE) (11) Concurrency (1) Constraints (8) Data types (11) FILESTREAM (22) General database design (104) Partitioning (13) Relationships and dependencies (12) Temporal tables (12) Views (16) ▼Database development (418) Comparison (4) Continuous delivery (CD) (5) Continuous integration (CI) (11) Development (146) Functions (106) Hyper-V (1) Search (10) Source Control (15) SQL unit testing (23) Stored procedures (34) String Concatenation (2) Synonyms (1) Team Explorer (2) Testing (35) Visual Studio (14) DBAtools (35) DevOps (23) DevSecOps (2) Documentation (22) ETL (76) ►Features (213) Adaptive query processing (11) Bulk insert (16) Database mail (10) DBCC (7) Experimentation Assistant (DEA) (3) High Availability (36) Query store (10) Replication (40) Transaction log (59) Transparent Data Encryption (TDE) (21) Importing, exporting (51) Installation, setup and configuration (121) Jobs (42) ▼Languages and coding (686) Cursors (9) DDL (9) DML (6) JSON (17) PowerShell (77) Python (37) R (16) SQL commands (196) SQLCMD (7) String functions (21) T-SQL (275) XML (15) Lists (12) Machine learning (37) Maintenance (99) Migration (50) Miscellaneous (1) ►Performance tuning (869) Alerting (8) Always On Availability Groups (82) Buffer Pool Extension (BPE) (9) Columnstore index (9) Deadlocks (16) Execution plans (125) In-Memory OLTP (22) Indexes (79) Latches (5) Locking (10) Monitoring (100) Performance (196) Performance counters (28) Performance Testing (9) Query analysis (121) Reports (20) SSAS monitoring (3) SSIS monitoring (10) SSRS monitoring (4) Wait types (11) ►Professional development (68) Professional development (27) Project management (9) SQL interview questions (32) Recovery (33) Security (84) Server management (24) SQL Azure (271) SQL Server Management Studio (SSMS) (90) SQL Server on Linux (21) ►SQL Server versions (177) SQL Server 2012 (6) SQL Server 2016 (63) SQL Server 2017 (49) SQL Server 2019 (57) SQL Server 2022 (2) ►Technologies (334) AWS (45) AWS RDS (56) Azure Cosmos DB (28) Containers (12) Docker (9) Graph database (13) Kerberos (2) Kubernetes (1) Linux (44) LocalDB (2) MySQL (49) Oracle (10) PolyBase (10) PostgreSQL (36) SharePoint (4) Ubuntu (13) Uncategorized (4) Utilities (21) Helpers and best practices BI performance counters SQL code smells rules SQL Server wait types © 2022 Quest Software Inc. ALL RIGHTS RESERVED. GDPR Terms of Use Privacy
Share:
0 comments

Comments (0)

Leave a Comment

Minimum 10 characters required

* All fields are required. Comments are moderated before appearing.

No comments yet. Be the first to comment!