USE [master]
GO
/****** Object:  StoredProcedure [dbo].[sp_indiciAndShrink]    Script Date: 03/11/2009 17:06:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		Marco Salvi
-- Create date: 11/03/2009
-- Description:	Stored procedure per ricostruire gli indici e fare lo shrink su un db
-- =============================================
CREATE PROCEDURE [dbo].[sp_indiciAndShrink] 
(
	@databaseName sysname
)
AS
BEGIN
	
	exec('USE ' + @databaseName)
	
	-- elimino eventuale tab temporanea preesistente
	IF (SELECT COUNT(*) FROM TEMPDB..SYSOBJECTS WHERE NAME = '##TMP_nomiTabelle') > 0
	  BEGIN
		DROP TABLE ##TMP_nomiTabelle
	  END

	-- enumero le tab del db in una tab temporanea
	SELECT	IDENT = IDENTITY (INT,1,1), name
	INTO ##TMP_nomiTabelle
	FROM sys.Tables

	-- eseguo reindicizzazione
	DECLARE @VAR1 INT
	SET @VAR1 = 1
	WHILE @VAR1 < = ( SELECT COUNT(*) FROM ##TMP_nomiTabelle)
	BEGIN 
		
		DECLARE @OBJECTNAME VARCHAR(256)
		
		-- carico il nome della tab i-esima
		SELECT	@OBJECTNAME = name
		FROM	##TMP_nomiTabelle 
		WHERE	[IDENT] = @VAR1
		
		-- rebuild indice
		DBCC DBREINDEX(@OBJECTNAME)

		-- incremento
		SET @VAR1 = @VAR1 + 1

	END

	--shrink del db
	DBCC SHRINKDATABASE (@databaseName)

END