แก้ไข

sys.sp_refreshview (Transact-SQL)

Applies to: SQL Server Azure SQL Database Azure SQL Managed Instance SQL analytics endpoint in Microsoft Fabric Warehouse in Microsoft Fabric SQL database in Microsoft Fabric

The sys.sp_refreshview system stored procedure updates the metadata for the specified non-schema-bound view. Persistent metadata for a view can become outdated because of changes to the underlying objects upon which the view depends.

Transact-SQL syntax conventions

Syntax

sys.sp_refreshview [ @viewname = ] N'viewname'
[ ; ]

Arguments

[ @viewname = ] N'viewname'

The name of the view. @viewname is nvarchar, with no default. @viewname can be a multipart identifier, but can only refer to views in the current database.

Return code values

0 (success) or a nonzero number (failure).

Remarks

If you don't create a view with SCHEMABINDING, run sp_refreshview when you make changes to the objects underlying the view that affect the definition of the view. Otherwise, the view might return unexpected results when you query it.

Permissions

Requires ALTER permission on the view, and REFERENCES permission on common language runtime (CLR) user-defined types and XML schema collections that the view columns reference.

Examples

The code samples in this article use the AdventureWorks2025, AdventureWorksDW2025, or AdventureWorksLT2025 sample database, which you can download from the Azure Data SQL Samples Repository GitHub repository.

A. Update the metadata of a view

The following example refreshes the metadata for the view Sales.vIndividualCustomer.

USE AdventureWorks2025;
GO

EXECUTE sp_refreshview N'Sales.vIndividualCustomer';

B. Create a script that updates all views that have dependencies on a changed object

Assume that the table Person.Person was changed in a way that affects the definition of any views on it. The following example creates a script that refreshes the metadata for all views that depend on the table Person.Person.

USE AdventureWorks2025;
GO

SELECT DISTINCT 'EXECUTE sp_refreshview ''' + name + ''''
FROM sys.objects AS so
     INNER JOIN sys.sql_expression_dependencies AS sed
         ON so.object_id = sed.referencing_id
WHERE so.type = 'V'
      AND sed.referenced_id = OBJECT_ID('Person.Person');