Powerbuilder pour les completement Geeks !

Le forum (ô combien francophone) des utilisateurs de Powerbuilder.

Recherche rapide

Annonce

Certaines rubriques, dont des cours, sont uniquement visibles par les membres du forum ^^.
Dans la rubrique Liens & Références, vous avez accès à un sommaire de téléchargement, profitez-en !
Il existe maintenant un nouveau TOPIC "Votre CV en Ligne" accessible uniquement par demande.

#1 18-06-2008 18:57:40

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

[SOURCE] Quelques scripts utiles pour Sql server

Generer un script d'insert ...
Tester sur SQL Server 7.0 and SQL Server 2000 and SQL Server 2005

Code: sql

SET NOCOUNT ON
GO

PRINT 'Using Master database'
USE master
GO

PRINT 'Checking for the existence of this procedure'
IF (SELECT OBJECT_ID('sp_generate_inserts','P')) IS NOT NULL --means, the procedure already exists
  BEGIN
    PRINT 'Procedure already exists. So, dropping it'
    DROP PROC sp_generate_inserts
  END
GO

CREATE PROC sp_generate_inserts
(
  @table_name varchar(776),      -- The table/view for which the INSERT statements will be generated using the existing data
  @target_table varchar(776) = NULL,   -- Use this parameter to specify a different table name into which the data will be inserted
  @include_column_list bit = 1,    -- Use this parameter to include/ommit column list in the generated INSERT statement
  @from varchar(800) = NULL,     -- Use this parameter to filter the rows based on a filter condition (using WHERE)
  @include_timestamp bit = 0,     -- Specify 1 for this parameter, if you want to include the TIMESTAMP/ROWVERSION column's data in the INSERT statement
  @debug_mode bit = 0,      -- If @debug_mode is set to 1, the SQL statements constructed by this procedure will be printed for later examination
  @owner varchar(64) = NULL,    -- Use this parameter if you are not the owner of the table
  @ommit_images bit = 0,      -- Use this parameter to generate INSERT statements by omitting the 'image' columns
  @ommit_identity bit = 0,    -- Use this parameter to ommit the identity columns
  @top int = NULL,      -- Use this parameter to generate INSERT statements only for the TOP n rows
  @cols_to_include varchar(8000) = NULL,  -- List of columns to be included in the INSERT statement
  @cols_to_exclude varchar(8000) = NULL,  -- List of columns to be excluded from the INSERT statement
  @disable_constraints bit = 0,    -- When 1, disables foreign key constraints and enables them after the INSERT statements
  @ommit_computed_cols bit = 0    -- When 1, computed columns will not be included in the INSERT statement
  
)
AS
BEGIN



SET NOCOUNT ON

--Making sure user only uses either @cols_to_include or @cols_to_exclude
IF ((@cols_to_include IS NOT NULL) AND (@cols_to_exclude IS NOT NULL))
  BEGIN
    RAISERROR('Use either @cols_to_include or @cols_to_exclude. Do not use both the parameters at once',16,1)
    RETURN -1 --Failure. Reason: Both @cols_to_include and @cols_to_exclude parameters are specified
  END

--Making sure the @cols_to_include and @cols_to_exclude parameters are receiving values in proper format
IF ((@cols_to_include IS NOT NULL) AND (PATINDEX('''%''',@cols_to_include) = 0))
  BEGIN
    RAISERROR('Invalid use of @cols_to_include property',16,1)
    PRINT 'Specify column names surrounded by single quotes and separated by commas'
    PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_include = "''title_id'',''title''"'
    RETURN -1 --Failure. Reason: Invalid use of @cols_to_include property
  END

IF ((@cols_to_exclude IS NOT NULL) AND (PATINDEX('''%''',@cols_to_exclude) = 0))
  BEGIN
    RAISERROR('Invalid use of @cols_to_exclude property',16,1)
    PRINT 'Specify column names surrounded by single quotes and separated by commas'
    PRINT 'Eg: EXEC sp_generate_inserts titles, @cols_to_exclude = "''title_id'',''title''"'
    RETURN -1 --Failure. Reason: Invalid use of @cols_to_exclude property
  END


--Checking to see if the database name is specified along wih the table name
--Your database context should be local to the table for which you want to generate INSERT statements
--specifying the database name is not allowed
IF (PARSENAME(@table_name,3)) IS NOT NULL
  BEGIN
    RAISERROR('Do not specify the database name. Be in the required database and just specify the table name.',16,1)
    RETURN -1 --Failure. Reason: Database name is specified along with the table name, which is not allowed
  END

--Checking for the existence of 'user table' or 'view'
--This procedure is not written to work on system tables
--To script the data in system tables, just create a view on the system tables and script the view instead

IF @owner IS NULL
  BEGIN
    IF ((OBJECT_ID(@table_name,'U') IS NULL) AND (OBJECT_ID(@table_name,'V') IS NULL)) 
      BEGIN
        RAISERROR('User table or view not found.',16,1)
        PRINT 'You may see this error, if you are not the owner of this table or view. In that case use @owner parameter to specify the owner name.'
        PRINT 'Make sure you have SELECT permission on that table or view.'
        RETURN -1 --Failure. Reason: There is no user table or view with this name
      END
  END
ELSE
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @table_name AND (TABLE_TYPE = 'BASE TABLE' OR TABLE_TYPE = 'VIEW') AND TABLE_SCHEMA = @owner)
      BEGIN
        RAISERROR('User table or view not found.',16,1)
        PRINT 'You may see this error, if you are not the owner of this table. In that case use @owner parameter to specify the owner name.'
        PRINT 'Make sure you have SELECT permission on that table or view.'
        RETURN -1 --Failure. Reason: There is no user table or view with this name    
      END
  END

--Variable declarations
DECLARE    @Column_ID int,     
    @Column_List varchar(8000), 
    @Column_Name varchar(128), 
    @Start_Insert varchar(786), 
    @Data_Type varchar(128), 
    @Actual_Values varchar(8000),  --This is the string that will be finally executed to generate INSERT statements
    @IDN varchar(128)    --Will contain the IDENTITY column's name in the table

--Variable Initialization
SET @IDN = ''
SET @Column_ID = 0
SET @Column_Name = ''
SET @Column_List = ''
SET @Actual_Values = ''

IF @owner IS NULL 
  BEGIN
    SET @Start_Insert = 'INSERT INTO ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' 
  END
ELSE
  BEGIN
    SET @Start_Insert = 'INSERT ' + '[' + LTRIM(RTRIM(@owner)) + '].' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']'     
  END


--To get the first column's ID

SELECT  @Column_ID = MIN(ORDINAL_POSITION)   
FROM  INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
WHERE   TABLE_NAME = @table_name AND
(@owner IS NULL OR TABLE_SCHEMA = @owner)



--Loop through all the columns of the table, to get the column names and their data types
WHILE @Column_ID IS NOT NULL
  BEGIN
    SELECT   @Column_Name = QUOTENAME(COLUMN_NAME), 
    @Data_Type = DATA_TYPE 
    FROM   INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
    WHERE   ORDINAL_POSITION = @Column_ID AND 
    TABLE_NAME = @table_name AND
    (@owner IS NULL OR TABLE_SCHEMA = @owner)



    IF @cols_to_include IS NOT NULL --Selecting only user specified columns
    BEGIN
      IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_include) = 0 
      BEGIN
        GOTO SKIP_LOOP
      END
    END

    IF @cols_to_exclude IS NOT NULL --Selecting only user specified columns
    BEGIN
      IF CHARINDEX( '''' + SUBSTRING(@Column_Name,2,LEN(@Column_Name)-2) + '''',@cols_to_exclude) <> 0 
      BEGIN
        GOTO SKIP_LOOP
      END
    END

    --Making sure to output SET IDENTITY_INSERT ON/OFF in case the table has an IDENTITY column
    IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsIdentity')) = 1 
    BEGIN
      IF @ommit_identity = 0 --Determing whether to include or exclude the IDENTITY column
        SET @IDN = @Column_Name
      ELSE
        GOTO SKIP_LOOP      
    END
    
    --Making sure whether to output computed columns or not
    IF @ommit_computed_cols = 1
    BEGIN
      IF (SELECT COLUMNPROPERTY( OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name),SUBSTRING(@Column_Name,2,LEN(@Column_Name) - 2),'IsComputed')) = 1 
      BEGIN
        GOTO SKIP_LOOP          
      END
    END
    
    --Tables with columns of IMAGE data type are not supported for obvious reasons
    IF(@Data_Type in ('image'))
      BEGIN
        IF (@ommit_images = 0)
          BEGIN
            RAISERROR('Tables with image columns are not supported.',16,1)
            PRINT 'Use @ommit_images = 1 parameter to generate INSERTs for the rest of the columns.'
            PRINT 'DO NOT ommit Column List in the INSERT statements. If you ommit column list using @include_column_list=0, the generated INSERTs will fail.'
            RETURN -1 --Failure. Reason: There is a column with image data type
          END
        ELSE
          BEGIN
          GOTO SKIP_LOOP
          END
      END

    --Determining the data type of the column and depending on the data type, the VALUES part of
    --the INSERT statement is generated. Care is taken to handle columns with NULL values. Also
    --making sure, not to lose any data from flot, real, money, smallmomey, datetime columns
    SET @Actual_Values = @Actual_Values  +
    CASE 
      WHEN @Data_Type IN ('char','varchar','nchar','nvarchar') 
        THEN 
          'COALESCE('''''''' + REPLACE(RTRIM(' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'
      WHEN @Data_Type IN ('datetime','smalldatetime') 
        THEN 
          'COALESCE('''''''' + RTRIM(CONVERT(char,' + @Column_Name + ',109))+'''''''',''NULL'')'
      WHEN @Data_Type IN ('uniqueidentifier') 
        THEN  
          'COALESCE('''''''' + REPLACE(CONVERT(char(255),RTRIM(' + @Column_Name + ')),'''''''','''''''''''')+'''''''',''NULL'')'
      WHEN @Data_Type IN ('text','ntext') 
        THEN  
          'COALESCE('''''''' + REPLACE(CONVERT(char(8000),' + @Column_Name + '),'''''''','''''''''''')+'''''''',''NULL'')'          
      WHEN @Data_Type IN ('binary','varbinary') 
        THEN  
          'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
      WHEN @Data_Type IN ('timestamp','rowversion') 
        THEN  
          CASE 
            WHEN @include_timestamp = 0 
              THEN 
                '''DEFAULT''' 
              ELSE 
                'COALESCE(RTRIM(CONVERT(char,' + 'CONVERT(int,' + @Column_Name + '))),''NULL'')'  
          END
      WHEN @Data_Type IN ('float','real','money','smallmoney')
        THEN
          'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ',2)' + ')),''NULL'')' 
      ELSE 
        'COALESCE(LTRIM(RTRIM(' + 'CONVERT(char, ' +  @Column_Name  + ')' + ')),''NULL'')' 
    END   + '+' +  ''',''' + ' + '
    
    --Generating the column list for the INSERT statement
    SET @Column_List = @Column_List +  @Column_Name + ','  

    SKIP_LOOP: --The label used in GOTO

    SELECT   @Column_ID = MIN(ORDINAL_POSITION) 
    FROM   INFORMATION_SCHEMA.COLUMNS (NOLOCK) 
    WHERE   TABLE_NAME = @table_name AND 
    ORDINAL_POSITION > @Column_ID AND
    (@owner IS NULL OR TABLE_SCHEMA = @owner)


  --Loop ends here!
  END

--To get rid of the extra characters that got concatenated during the last run through the loop
SET @Column_List = LEFT(@Column_List,len(@Column_List) - 1)
SET @Actual_Values = LEFT(@Actual_Values,len(@Actual_Values) - 6)

IF LTRIM(@Column_List) = '' 
  BEGIN
    RAISERROR('No columns to select. There should at least be one column to generate the output',16,1)
    RETURN -1 --Failure. Reason: Looks like all the columns are ommitted using the @cols_to_exclude parameter
  END

--Forming the final string that will be executed, to output the INSERT statements
IF (@include_column_list <> 0)
  BEGIN
    SET @Actual_Values = 
      'SELECT ' +  
      CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
      '''' + RTRIM(@Start_Insert) + 
      ' ''+' + '''(' + RTRIM(@Column_List) +  '''+' + ''')''' + 
      ' +''VALUES(''+ ' +  @Actual_Values  + '+'')''' + ' ' + 
      COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
  END
ELSE IF (@include_column_list = 0)
  BEGIN
    SET @Actual_Values = 
      'SELECT ' + 
      CASE WHEN @top IS NULL OR @top < 0 THEN '' ELSE ' TOP ' + LTRIM(STR(@top)) + ' ' END + 
      '''' + RTRIM(@Start_Insert) + 
      ' '' +''VALUES(''+ ' +  @Actual_Values + '+'')''' + ' ' + 
      COALESCE(@from,' FROM ' + CASE WHEN @owner IS NULL THEN '' ELSE '[' + LTRIM(RTRIM(@owner)) + '].' END + '[' + rtrim(@table_name) + ']' + '(NOLOCK)')
  END  

--Determining whether to ouput any debug information
IF @debug_mode =1
  BEGIN
    PRINT '/*****START OF DEBUG INFORMATION*****'
    PRINT 'Beginning of the INSERT statement:'
    PRINT @Start_Insert
    PRINT ''
    PRINT 'The column list:'
    PRINT @Column_List
    PRINT ''
    PRINT 'The SELECT statement executed to generate the INSERTs'
    PRINT @Actual_Values
    PRINT ''
    PRINT '*****END OF DEBUG INFORMATION*****/'
    PRINT ''
  END
    
PRINT '--INSERTs generated by ''sp_generate_inserts'' stored procedure written by Vyas'
PRINT '--Build number: 22'
PRINT '--Problems/Suggestions? Contact Vyas @ vyaskn@hotmail.com'
PRINT '--http://vyaskn.tripod.com'
PRINT ''
PRINT 'SET NOCOUNT ON'
PRINT ''


--Determining whether to print IDENTITY_INSERT or not
IF (@IDN <> '')
  BEGIN
    PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' ON'
    PRINT 'GO'
    PRINT ''
  END


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
  BEGIN
    IF @owner IS NULL
      BEGIN
        SELECT   'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
      END
    ELSE
      BEGIN
        SELECT   'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' NOCHECK CONSTRAINT ALL' AS '--Code to disable constraints temporarily'
      END

    PRINT 'GO'
  END

PRINT ''
PRINT 'PRINT ''Inserting values into ' + '[' + RTRIM(COALESCE(@target_table,@table_name)) + ']' + ''''


--All the hard work pays off here!!! You'll get your INSERT statements, when the next line executes!
EXEC (@Actual_Values)

PRINT 'PRINT ''Done'''
PRINT ''


IF @disable_constraints = 1 AND (OBJECT_ID(QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + @table_name, 'U') IS NOT NULL)
  BEGIN
    IF @owner IS NULL
      BEGIN
        SELECT   'ALTER TABLE ' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL'  AS '--Code to enable the previously disabled constraints'
      END
    ELSE
      BEGIN
        SELECT   'ALTER TABLE ' + QUOTENAME(@owner) + '.' + QUOTENAME(COALESCE(@target_table, @table_name)) + ' CHECK CONSTRAINT ALL' AS '--Code to enable the previously disabled constraints'
      END

    PRINT 'GO'
  END

PRINT ''
IF (@IDN <> '')
  BEGIN
    PRINT 'SET IDENTITY_INSERT ' + QUOTENAME(COALESCE(@owner,USER_NAME())) + '.' + QUOTENAME(@table_name) + ' OFF'
    PRINT 'GO'
  END

PRINT 'SET NOCOUNT OFF'


SET NOCOUNT OFF
RETURN 0 --Success. We are done!
END

GO

PRINT 'Created the procedure'
GO


--Mark procedure as system object
EXEC sys.sp_MS_marksystemobject sp_generate_inserts
GO

PRINT 'Granting EXECUTE permission on sp_generate_inserts to all users'
GRANT EXEC ON sp_generate_inserts TO public

SET NOCOUNT OFF
GO

PRINT 'Done'

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#2 18-06-2008 19:00:01

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Drop de l'ensemble des triggers d'un BDD
Sql server 2000

Code: sql

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspDropAllTriggers]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspDropAllTriggers] 
GO 

CREATE PROCEDURE uspDropAllTriggers AS 

declare @objectname varchar(300) 
declare @objectname2 varchar(300) 
DECLARE objectCursor CURSOR FOR 
  SELECT a1.NAME, a2.name
  FROM sysobjects a1, sysobjects a2
  WHERE a1.type IN ( 'TR') 
  AND a1.status >0  
  AND a2.id = a1.parent_obj 
  ORDER BY 2,1


declare @toto int

OPEN objectCursor 
FETCH NEXT FROM objectCursor INTO @objectname , @objectname2
WHILE (@@fetch_status <> -1) BEGIN 
  -- exec( 'DROP TRIGGER ' + @objectname + ' ')  
    Print '-- ' + @objectname2
    print ' DROP Trigger '+ @objectname + ';'
    print ' GO '
  FETCH NEXT FROM objectCursor INTO @objectname , @objectname2
END 
DEALLOCATE objectCursor 
GO 

exec uspDropAllTriggers 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspDropAllTriggers]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspDropAllTriggers] 
GO



Sql server 2005

Code: sql

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspDropAllTriggers]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspDropAllTriggers] 
GO 

CREATE PROCEDURE uspDropAllTriggers AS 

declare @objectname varchar(300) 
declare @objectname2 varchar(300) 
DECLARE objectCursor CURSOR FOR 
  SELECT a1.NAME, a2.name
  FROM sysobjects a1, sysobjects a2
  WHERE a1.type IN ( 'TR') 
  AND a2.id = a1.parent_obj 
  ORDER BY 2,1


declare @toto int

OPEN objectCursor 
FETCH NEXT FROM objectCursor INTO @objectname , @objectname2
WHILE (@@fetch_status <> -1) BEGIN 
  -- exec( 'DROP TRIGGER ' + @objectname + ' ')  
    Print '-- ' + @objectname2
    print ' DROP Trigger '+ @objectname + ';'
    print ' GO '
  FETCH NEXT FROM objectCursor INTO @objectname , @objectname2
END 
DEALLOCATE objectCursor 
GO 

exec uspDropAllTriggers 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspDropAllTriggers]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspDropAllTriggers] 
GO

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#3 18-06-2008 19:03:35

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Recompilation des objets invalides et refrech des vues

Sqlserver 2000

Code: sql

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRefreshDatabase]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRefreshDatabase] 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRecompileAllProcedures]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRecompileAllProcedures] 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRefreshAllViews]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRefreshAllViews] 
GO 


CREATE   PROCEDURE uspRefreshAllViews AS 

declare @toto int

declare @objectname varchar(300) 
DECLARE objectCursor CURSOR local FOR SELECT name 
FROM sysobjects 
WHERE type IN ('V')
 AND status > 0 

OPEN objectCursor 
FETCH NEXT FROM objectCursor INTO 
 @objectname 
WHILE (@@fetch_status <> -1) BEGIN 
--    exec  @toto  = sp_refreshview @objectname 
    print ' exec  sp_refreshview ['+ @objectname + '];'
    print ' GO'
  -- exec( 'select count(*) from ' + @objectname) 
  FETCH NEXT FROM objectCursor INTO  @objectname 
END 
DEALLOCATE objectCursor 
GO 


CREATE PROCEDURE uspRecompileAllProcedures AS 

declare @objectname varchar(300) 
DECLARE objectCursor CURSOR FOR SELECT name 
FROM sysobjects 
WHERE type IN ('P', 'V', 'TR') 
AND status >0 

declare @toto int

OPEN objectCursor 
FETCH NEXT FROM objectCursor INTO @objectname 
WHILE (@@fetch_status <> -1) BEGIN 
--   exec @toto = sp_recompile @objectname 
    print ' exec  sp_recompile ['+ @objectname + '];'
    print ' GO'
--  If @toto <> 0
--    print @objectname 
  FETCH NEXT FROM objectCursor INTO @objectname 
END 
DEALLOCATE objectCursor 
GO 

exec uspRefreshAllViews 
exec uspRecompileAllProcedures 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRefreshDatabase]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRefreshDatabase] 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRecompileAllProcedures]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRecompileAllProcedures] 
GO



Sqlserver 2005

Code: sql

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRefreshDatabase]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRefreshDatabase] 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRecompileAllProcedures]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRecompileAllProcedures] 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRefreshAllViews]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRefreshAllViews] 
GO 


CREATE   PROCEDURE uspRefreshAllViews AS 

declare @toto int

declare @objectname varchar(300) 
DECLARE objectCursor CURSOR local FOR SELECT name 
FROM sysobjects 
WHERE type IN ('V')
-- AND status > 0 

OPEN objectCursor 
FETCH NEXT FROM objectCursor INTO 
 @objectname 
WHILE (@@fetch_status <> -1) BEGIN 
--    exec  @toto  = sp_refreshview @objectname 
    print ' exec  sp_refreshview ['+ @objectname + '];'
    print ' GO'
  -- exec( 'select count(*) from ' + @objectname) 
  FETCH NEXT FROM objectCursor INTO  @objectname 
END 
DEALLOCATE objectCursor 
GO 


CREATE PROCEDURE uspRecompileAllProcedures AS 

declare @objectname varchar(300) 
DECLARE objectCursor CURSOR FOR SELECT name 
FROM sysobjects 
WHERE type IN ('P', 'V', 'TR') 
--AND status >0 

declare @toto int

OPEN objectCursor 
FETCH NEXT FROM objectCursor INTO @objectname 
WHILE (@@fetch_status <> -1) BEGIN 
--   exec @toto = sp_recompile @objectname 
    print ' exec  sp_recompile ['+ @objectname + '];'
    print ' GO'
--  If @toto <> 0
--    print @objectname 
  FETCH NEXT FROM objectCursor INTO @objectname 
END 
DEALLOCATE objectCursor 
GO 

exec uspRefreshAllViews 
exec uspRecompileAllProcedures 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRefreshDatabase]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRefreshDatabase] 
GO 

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[uspRecompileAllProcedures]')  
and OBJECTPROPERTY(id, N'IsProcedure') = 1) 
drop procedure [dbo].[uspRecompileAllProcedures] 
GO

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#4 18-06-2008 19:07:16

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Desactiver l'ensemble des triggers d'une base

sqlserver 2000

Code: sql

CREATE  PROCEDURE uspDisableAllTrigger AS  

declare @objectname varchar(300)  
DECLARE objectCursor CURSOR local FOR SELECT name  
FROM sysobjects  
WHERE type IN ('U') AND status > 0  

OPEN objectCursor  
FETCH NEXT FROM objectCursor INTO  
 @objectname  
WHILE (@@fetch_status <> -1) BEGIN  
  print @objectname  
  exec( 'ALTER TABLE ' + @objectname + ' DISABLE TRIGGER ALL')  
  FETCH NEXT FROM objectCursor INTO  @objectname  
END  
DEALLOCATE objectCursor  
GO  


CREATE  PROCEDURE uspEnableAllTrigger AS  

declare @objectname varchar(300)  
DECLARE objectCursor CURSOR local FOR SELECT name  
FROM sysobjects  
WHERE type IN ('U') AND status > 0  

OPEN objectCursor  
FETCH NEXT FROM objectCursor INTO  
 @objectname  
WHILE (@@fetch_status <> -1) BEGIN  
  print @objectname  
  exec( 'ALTER TABLE ' + @objectname + ' ENABLE TRIGGER ALL')  
  FETCH NEXT FROM objectCursor INTO  @objectname  
END  
DEALLOCATE objectCursor  
GO



sqlserver 2005

Code: sql

CREATE  PROCEDURE uspDisableAllTrigger AS  

declare @objectname varchar(300)  
DECLARE objectCursor CURSOR local FOR SELECT name  
FROM sysobjects  
WHERE type IN ('U') 

OPEN objectCursor  
FETCH NEXT FROM objectCursor INTO  
 @objectname  
WHILE (@@fetch_status <> -1) BEGIN  
  print @objectname  
  exec( 'ALTER TABLE ' + @objectname + ' DISABLE TRIGGER ALL')  
  FETCH NEXT FROM objectCursor INTO  @objectname  
END  
DEALLOCATE objectCursor  
GO  


CREATE  PROCEDURE uspEnableAllTrigger AS  

declare @objectname varchar(300)  
DECLARE objectCursor CURSOR local FOR SELECT name  
FROM sysobjects  
WHERE type IN ('U') 

OPEN objectCursor  
FETCH NEXT FROM objectCursor INTO  
 @objectname  
WHILE (@@fetch_status <> -1) BEGIN  
  print @objectname  
  exec( 'ALTER TABLE ' + @objectname + ' ENABLE TRIGGER ALL')  
  FETCH NEXT FROM objectCursor INTO  @objectname  
END  
DEALLOCATE objectCursor  
GO

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#5 18-06-2008 19:10:03

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Generation des user d'un server

SQL 7 / SQL 2000 / SQL 2005

Code: sql

/***********************************************************************
*************************
*
* Purpose: To capture all the SQL Server logins
with the binary password regardless of SQL version. 
* Need to save the results

************************************************************************
************************/

USE master
GO
IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
DROP PROCEDURE sp_hexadecimal
GO
CREATE PROCEDURE sp_hexadecimal
@binvalue varbinary(256),
@hexvalue varchar(256) OUTPUT
AS
DECLARE @charvalue varchar(256)
DECLARE @i int
DECLARE @length int
DECLARE @hexstring char(16)
SELECT @charvalue = '0x'
SELECT @i = 1
SELECT @length = DATALENGTH (@binvalue)
SELECT @hexstring = '0123456789ABCDEF'
WHILE (@i <= @length)
BEGIN
DECLARE @tempint int
DECLARE @firstint int
DECLARE @secondint int
SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))
SELECT @firstint = FLOOR(@tempint/16)
SELECT @secondint = @tempint - (@firstint*16)
SELECT @charvalue = @charvalue +
SUBSTRING(@hexstring, @firstint+1, 1) +
SUBSTRING(@hexstring, @secondint+1, 1)
SELECT @i = @i + 1
END
SELECT @hexvalue = @charvalue
GO

IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
DROP PROCEDURE sp_help_revlogin
GO
CREATE PROCEDURE sp_help_revlogin @login_name sysname = NULL AS
DECLARE @name sysname
DECLARE @xstatus int
DECLARE @binpwd varbinary (256)
DECLARE @txtpwd sysname
DECLARE @tmpstr varchar (256)
DECLARE @SID_varbinary varbinary(85)
DECLARE @SID_string varchar(256)

IF (@login_name IS NULL)
DECLARE login_curs CURSOR FOR
SELECT sid, name, xstatus, password FROM
master..sysxlogins
WHERE srvid IS NULL AND name <> 'sa'
ELSE
DECLARE login_curs CURSOR FOR
SELECT sid, name, xstatus, password FROM
master..sysxlogins
WHERE srvid IS NULL AND name = @login_name
OPEN login_curs
FETCH NEXT FROM login_curs INTO @SID_varbinary, @name, @xstatus,
@binpwd
IF (@@fetch_status = -1)
BEGIN
PRINT 'No login(s) found.'
CLOSE login_curs
DEALLOCATE login_curs
RETURN -1
END
SET @tmpstr = '/* sp_help_revlogin script '
PRINT @tmpstr
SET @tmpstr = '** Generated '
+ CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
PRINT 'DECLARE @pwd sysname'
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
PRINT ''
SET @tmpstr = '-- Login: ' + @name
PRINT @tmpstr
IF (@xstatus & 4) = 4
BEGIN -- NT authenticated account/group
IF (@xstatus & 1) = 1
BEGIN -- NT login is denied access
SET @tmpstr = 'EXEC master..sp_denylogin ''' +
@name + ''''
PRINT @tmpstr
END
ELSE BEGIN -- NT login has access
SET @tmpstr = 'EXEC master..sp_grantlogin ''' +
@name + ''''
PRINT @tmpstr
END
END
ELSE BEGIN -- SQL Server authentication
IF (@binpwd IS NOT NULL)
BEGIN -- Non-null password
EXEC sp_hexadecimal @binpwd, @txtpwd OUT
IF (@xstatus & 2048) = 2048
SET @tmpstr = 'SET @pwd = CONVERT
(varchar(256), ' + @txtpwd + ')'
ELSE
SET @tmpstr = 'SET @pwd = CONVERT
(varbinary(256), ' + @txtpwd + ')'
PRINT @tmpstr
EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
SET @tmpstr = 'EXEC master..sp_addlogin ''' +
@name
+ ''', @pwd, @sid = ' + @SID_string + ',
@encryptopt = '
END
ELSE BEGIN
-- Null password
EXEC sp_hexadecimal @SID_varbinary,@SID_string OUT
SET @tmpstr = 'EXEC master..sp_addlogin ''' +
@name
+ ''', NULL, @sid = ' + @SID_string + ',
@encryptopt = '
END
IF (@xstatus & 2048) = 2048
-- login upgraded from 6.5
SET @tmpstr = @tmpstr +
'''skip_encryption_old'''
ELSE
SET @tmpstr = @tmpstr + '''skip_encryption'''
PRINT @tmpstr
END
END
FETCH NEXT FROM login_curs INTO @SID_varbinary, @name,
@xstatus, @binpwd
END
CLOSE login_curs
DEALLOCATE login_curs
RETURN 0
GO
IF OBJECT_ID ('seeMigrateSQLLogins') IS NOT NULL
DROP PROCEDURE seeMigrateSQLLogins
GO
create procedure seeMigrateSQLLogins @login_name sysname = NULL
as
declare
@name char(50),
@binpwd varbinary (256),
@txtpwd sysname,
@tmpstr varchar (256),
@SID_varbinary varbinary(85),
@SID_string varchar(256),
@Is_Policy bit,
@Is_Exp bit,
@type char(1),
@Pol char(3),
@Exp char(3)
set nocount on
create table #logins (
[name] nvarchar(128) NOT NULL,
[sid] varbinary(85) NOT NULL,
[type] char(1) NOT NULL,
[is_policy_checked] bit default 0,
[is_expiration_checked] bit default 0,
[password_hash] varbinary(256) )
insert #logins (name, sid, type)
select name, sid, type from sys.server_principals where 
(type_desc = 'SQL_LOGIN' or type_desc = 'WINDOWS_LOGIN')
and name <> 'sa' and name <> 'NT AUTHORITY\SYSTEM'
update a set a.is_policy_checked = b.is_policy_checked,
a.is_expiration_checked = b.is_expiration_checked, a.password_hash =
b.password_hash
from #logins a, sys.sql_Logins b
where a.sid = b.sid
set nocount off
IF (@login_name IS NULL) --Not a single user, get the list
DECLARE seelogin_curs CURSOR FOR
SELECT name, sid, password_hash, type,
is_policy_checked, is_expiration_checked FROM #logins
WHERE name <> 'sa'
ELSE
DECLARE seelogin_curs CURSOR FOR
SELECT name, sid, password_hash, type,
is_policy_checked, is_expiration_checked FROM #logins
WHERE name = @login_name
OPEN seelogin_curs
FETCH NEXT FROM seelogin_curs INTO @name, @SID_varbinary,
@binpwd, @type, @Is_Policy, @Is_Exp
IF (@@fetch_status = -1)
BEGIN
PRINT 'No login(s) found.'
CLOSE seelogin_curs
DEALLOCATE seelogin_curs
END
SET @tmpstr = '/* seeMigrateSQLLogins - For SQL Server 2005 Only
'
PRINT @tmpstr
SET @tmpstr = '** Generated '
+ CONVERT (varchar, GETDATE()) + ' on ' + @@SERVERNAME + ' */'
PRINT @tmpstr
PRINT ''
WHILE (@@fetch_status <> -1)
BEGIN
IF @type = 'S'
BEGIN
PRINT '/* SQL Login ******************/'
EXEC sp_hexadecimal @binpwd, @txtpwd OUT
EXEC sp_hexadecimal @SID_varbinary,
@SID_string OUT
IF @Is_Policy = 1 Begin set @Pol = 'ON'
End ELSE Begin set @Pol = 'OFF' END 
IF @Is_Exp = 1 Begin set @Exp = 'ON' End
ELSE Begin set @Exp = 'OFF' END 
SET @tmpstr = 'Create Login ' +
rtrim(@name) + ' WITH PASSWORD = ' + @txtpwd + ' hashed, sid = ' +
@SID_string + ', CHECK_POLICY = ' + @Pol + ', CHECK_EXPIRATION = ' +
@Exp
PRINT @tmpstr
PRINT ''
END
Else
BEGIN
PRINT '/* SQL Login ******************/'
EXEC sp_hexadecimal @SID_varbinary,
@SID_string OUT
SET @tmpstr = 'Create Login [' +
rtrim(@name) + '] FROM WINDOWS; '
PRINT @tmpstr
PRINT ''
END
FETCH NEXT FROM seelogin_curs INTO @name, @SID_varbinary,
@binpwd, @type, @Is_Policy, @Is_Exp
END
CLOSE seelogin_curs
DEALLOCATE seelogin_curs
drop table #logins
GO

declare
@version char(5)

--Get the current version of SQL Server running
select @version = substring(@@version,29,4)

if @version = '9.00'
Begin
exec seeMigrateSQLLogins
End
Else
begin
exec sp_help_revlogin
End

IF OBJECT_ID ('sp_hexadecimal') IS NOT NULL
DROP PROCEDURE sp_hexadecimal
GO
IF OBJECT_ID ('sp_help_revlogin') IS NOT NULL
DROP PROCEDURE sp_help_revlogin
GO
IF OBJECT_ID ('seeMigrateSQLLogins') IS NOT NULL
DROP PROCEDURE seeMigrateSQLLogins
GO
/* End Script */

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#6 24-06-2008 18:06:38

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

fragmentation

Code: sql

DECLARE @TableName sysname
DECLARE cur_showfragmentation CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
OPEN cur_showfragmentation
FETCH NEXT FROM cur_showfragmentation INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
  print 'Show fragmentation for the ' + @TableName + ' table'
  DBCC SHOWCONTIG (@TableName)
  FETCH NEXT FROM cur_showfragmentation INTO @TableName
END
CLOSE cur_showfragmentation
DEALLOCATE cur_showfragmentation

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#7 24-06-2008 18:18:40

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

fragmentation

Code: sql

DECLARE @TableName sysname
DECLARE cur_showfragmentation CURSOR FOR
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'
OPEN cur_showfragmentation
FETCH NEXT FROM cur_showfragmentation INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
  print 'Show fragmentation for the ' + @TableName + ' table'
  DBCC SHOWCONTIG (@TableName)
  FETCH NEXT FROM cur_showfragmentation INTO @TableName
END
CLOSE cur_showfragmentation
DEALLOCATE cur_showfragmentation

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#8 24-06-2008 18:21:41

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Recherche du mot XXXXXXXXXXXX dans les procedures, triggers et vues

Code: sql

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
DROP TABLE [dbo].[temp_jcz]
GO
CREATE TABLE [dbo].[temp_jcz](
  [Proc_id] [int] NULL,
  [Proc_Name] [sysname] NOT NULL,
  [Definition] [ntext] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]





 
-- get the names of the procedures that meet our criteria 
INSERT temp_jcz(Proc_id, Proc_Name) 
    SELECT id, OBJECT_NAME(id) 
        FROM syscomments 
        WHERE OBJECTPROPERTY(id, 'IsView') = 1 or 
              OBJECTPROPERTY(id, 'IsProcedure') = 1 or 
              OBJECTPROPERTY(id, 'IsTrigger') = 1 
        GROUP BY id, OBJECT_NAME(id) 
        -- HAVING COUNT(*) > 1 
 
-- initialize the NTEXT column so there is a pointer 
UPDATE temp_jcz SET Definition = '' 
 
-- declare local variables 
DECLARE  
    @txtPval binary(16),  
    @txtPidx INT,  
    @curName SYSNAME, 
    @curtext NVARCHAR(4000) 
 
-- set up a cursor, we need to be sure this is in the correct order 
-- from syscomments (which orders the 8KB chunks by colid) 
 
DECLARE c CURSOR 
    LOCAL FORWARD_ONLY STATIC READ_ONLY FOR 
    SELECT OBJECT_NAME(id), text 
        FROM syscomments s 
        INNER JOIN temp_jcz t 
        ON s.id = t.Proc_id 
        ORDER BY id, colid 
OPEN c 
FETCH NEXT FROM c INTO @curName, @curtext 
 
-- start the loop 
WHILE (@@FETCH_STATUS = 0) 
BEGIN 
 
    -- get the pointer for the current procedure name / colid 
    SELECT @txtPval = TEXTPTR(Definition) 
        FROM [temp_jcz] 
        WHERE Proc_Name = @curName 
 
    -- find out where to append the #temp table's value 
    SELECT @txtPidx = DATALENGTH(Definition)/2 
        FROM temp_jcz 
        WHERE Proc_Name = @curName 
 
    -- apply the append of the current 8KB chunk 
    UPDATETEXT temp_jcz.definition @txtPval @txtPidx 0 @curtext 
 
    FETCH NEXT FROM c INTO @curName, @curtext 
END 
 
 

CLOSE c 
DEALLOCATE  c

SELECT Proc_Name, Definition 
    FROM temp_jcz 
    WHERE upper(CONVERT(CHAR(5000),definition)) LIKE '%XXXXXXXXXXXX%'

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#9 21-07-2008 10:49:08

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Il n'existe pas de fonction SQL SERVER qui me permet non pas d'arrondir, mais de tronquer un decimale
Pour le faire

Code: sql

CREATE FUNCTION F_TRUNCATE_NUM (@N FLOAT, @DEC INT)
   RETURNS FLOAT
AS
BEGIN
 
IF @N IS NULL OR @DEC IS NULL
   RETURN NULL
 
IF @DEC < 0
   RETURN @N
 
RETURN FLOOR(@N * POWER(10, @DEC)) / POWER(10, @DEC)
 
END

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#10 20-08-2008 22:27:09

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Liste des requêtes en cours dans SQL Server ( avec compatibilité sqlserver 2000)

Code: sql

SELECT ES.session_id SPID,
               ER.blocking_session_id BlkBy,
               COUNT(*) Threads,
               DB_NAME(ER.database_id) BD,
               UPPER(ER.STATUS) Statut,
               ER.cpu_time / 1000 CPU,
               ER.reads Reads,
               ER.writes Writes,
               UPPER(ER.command) Commande,
               ESQLT.text SQLCommand
FROM sys.dm_exec_sessions ES (nolock)
JOIN sys.dm_exec_connections (nolock) EC ON ES.session_id = EC.session_id
JOIN sys.dm_exec_requests ER (nolock) ON ES.session_id = ER.session_id
JOIN sys.sysprocesses (nolock) SP ON SP.spid = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(ER.sql_handle) ESQLT
WHERE ES.program_name NOT LIKE 'DatabaseMail90%'
AND ES.session_id <> @@SPID
GROUP BY ES.session_id,
               ER.blocking_session_id,
               ER.database_id,
               ER.STATUS,
               ER.cpu_time / 1000,
               ER.reads,
               ER.writes,
               ER.command,
               ESQLT.text


Si vous avez un grand nombre (style 5 ou plus) dans la colonne Threads, c'est que SQL Server a décidé de paralléliser le traitement. Cela ne signifie pas forcément que votre requête est lente.
En revanche avec cela, vous allez pouvoir savoir quelle commande SQL est à l'origine de ce blocage (colonne SQLCommand).


Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#11 20-08-2008 22:31:32

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Indexes manquants

Code: sql

SELECT ROUND((MIGS.user_seeks + MIGS.user_scans) * MIGS.avg_total_user_cost * avg_user_impact, 0) Avantage,
               MIGS.unique_compiles Comp,
               MIGS.last_user_seek,
               MIGS.last_user_scan,
               REPLACE(REPLACE(MID.Statement, '[', ''), ']', '') 'Database.Schema.Table',
               REPLACE(REPLACE(MID.equality_columns, '[', ''), ']', '') Egalite,
               REPLACE(REPLACE(MID.inequality_columns, '[', ''), ']', '') Inegalite,
               REPLACE(REPLACE(MID.included_columns, '[', ''), ']', '') Incluse
FROM sys.dm_db_missing_index_group_stats MIGS
JOIN sys.dm_db_missing_index_groups MIG ON MIGS.GROUP_HANDLE = MIG.INDEX_GROUP_HANDLE
JOIN sys.dm_db_missing_index_details MID ON MIG.INDEX_HANDLE = MID.INDEX_HANDLE
WHERE CONVERT(CHAR(10), MIGS.LAST_USER_SEEK, 103) = CONVERT(CHAR(10), GETDATE(), 103)
AND DB_NAME(MID.database_id) NOT IN ('master', 'msdb', 'model', 'ReportServer', 'ReportServerTempDB', 'Distribution', 'TempDB')

creation de l'index comme suit:

Code: sql

CREATE INDEX IX_maTable_mesColonnes
ON maTable (listeDesColonnesEgalite+listeDesColonnesInegalite)
INCLUDE (listeDesColonnesIncluses)
WITH (FILLFACTOR = xx)

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

#12 20-08-2008 22:32:59

JCZ  
Builder Power
Award: bf
Lieu: 75019 paris
Date d'inscription: 21-05-2007
Messages: 1724
Pépites: 496,453,703,213
Banque: 9,223,372,036,854,775,808

Re: [SOURCE] Quelques scripts utiles pour Sql server

Voici une petite requête, qui relie l'utilisation des indexes (colonnes user_seeks, user_scans, user_lookups) à leur taux de fragmentation :

Code: sql

SELECT DB_NAME(IUS.database_id) DB, 
               OBJECT_NAME(IUS.object_id) TABLES,
               IDX.NAME IndexName,
               CAST(IPS.avg_fragmentation_in_percent AS NUMERIC(5,2)) Frag,
               CAST(IPS.avg_page_space_used_in_percent AS NUMERIC(5,2)) PgUsage,
               IPS.page_count Pg,
               IDX.fill_factor,
               IUS.user_seeks,
               IUS.user_scans,
               IUS.last_user_scan,
               IUS.last_user_seek,
               IUS.user_lookups,
               IUS.last_user_lookup,
               IDX.is_hypothetical,
               IDX.is_padded
FROM sys.dm_db_index_usage_stats IUS
JOIN sys.indexes IDX ON IUS.object_id = IDX.object_id
                                      AND IUS.index_id = IDX.index_id
JOIN sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(NULL), NULL, NULL, 'SAMPLED')IPS
        ON IUS.object_id = IPS.object_id
        AND IUS.index_id = IPS.index_id
WHERE OBJECT_NAME(IUS.object_id) NOT LIKE 'sys%'
AND IPS.index_id > 0

Face à l'agression, la puissance de l'intelligence

Hors ligne

 

Pied de page des forums

Propulsé par FluxBB 1.2.22