È possibile utilizzare un UDF come:
IF (SELECT [dbo].[Index_Exists] (N'SchemaName', N'TableName', N'IndexName')) = 0
BEGIN
-- Your script
END
Questa funzione assicura che l'indice si fa riferimento è quella giusta in quanto potrebbero utilizzare lo stesso indice e/o il nome della tabella per i diversi schemi:
CREATE FUNCTION [dbo].[Index_Exists] (@Schema_Name sysname, @Table_Name sysname, @Index_Name sysname)
RETURNS bit
WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @Output bit
SET @Schema_Name = ISNULL(@Schema_Name, N'dbo');
IF EXISTS (SELECT *
FROM sys.indexes ind
JOIN sys.index_columns ic ON ind.object_id = ic.object_id and ind.index_id = ic.index_id
JOIN sys.columns col ON ic.object_id = col.object_id and ic.column_id = col.column_id
JOIN sys.tables t ON ind.object_id = t.object_id
WHERE @Table_Name = t.[name]
AND @Schema_Name = OBJECT_SCHEMA_NAME(t.[object_id])
AND @Index_Name = ind.[name]
) SET @Output = CAST(1 as bit)
RETURN ISNULL(@Output,CAST(0 as bit))
END
fonte
2017-11-02 11:41:55
Vorrei che INFO_SCHEMA avesse effettivamente tutte le informazioni sullo schema –