sql编译与重编译
1.sp_recompile
使存储过程和触发器在下次运行时重新编译。
2.sp_refreshview
如果视图所依赖的基础对象发生更改(如:表增加了一个字段),则视图不会自动更新,这时需要调用该存储过程来对视图进行刷新。有人说,重新打开一下视图就可以更新视图,但我试了没有成功。
例1:刷新指定名称的视图
sp_refreshview 'v_tblItem'
例2:刷新整个数据库中的所有视图
CREATE PROCEDURE [dbo].[_Proc_CheckView](
@IsDelete bit=0 --是否要删除无效的视图
)
AS
BEGIN
DECLARE @vName sysname ;
DECLARE @ErrorMessage nvarchar(200);
DECLARE @count int;
SET @count=0;
DECLARE @ErrorCount int;
SET @ErrorCount=0;
CREATE TABLE #temp(
ViewName nvarchar(776)
)
DECLARE refresh_cursor CURSOR FOR
SELECT Name from sysobjects
WHERE xtype = 'V'
AND category=0
order by crdate
FOR READ ONLY
OPEN refresh_cursor
FETCH NEXT FROM refresh_cursor
INTO @vName
WHILE @@FETCH_STATUS = 0
BEGIN
BEGIN try
exec sys.sp_refreshview @vName
END try
BEGIN catch
insert into #temp(ViewName)
values( @vName)
SET @ErrorCount=@ErrorCount+1
IF(@IsDelete=1)
begin
DECLARE @sql nvarchar(500)
SET @sql='drop view '+ @vName
EXEC sp_executesql @sql
end
END catch
SET @count=@count+1;
FETCH NEXT FROM refresh_cursor
INTO @vName
END
CLOSE refresh_cursor
DEALLOCATE refresh_cursor
IF(@ErrorCount>0)
begin
select '本次共检查视图【'+Convert(nvarchar(20),@count)+'】个,其中有【'+Convert(nvarchar(20),@ErrorCount)+'】个无效,无效视图参见下表:'
SELECT * FROM #temp
END
ELSE
BEGIN
select '本次共检查视图【'+Convert(nvarchar(20),@count)+'】个,全部有效。'
END
DROP TABLE #temp
END
GO