
-- T_PLN_RESERVEBILL表索引创建脚本
BEGIN TRANSACTION;
GO

-- 动态生成表名+字段名的索引
DECLARE @table_name NVARCHAR(128) = 'T_PLN_RESERVEBILL';
DECLARE @sql NVARCHAR(MAX) = '';

SELECT @sql += 
    CASE WHEN NOT EXISTS (
        SELECT * FROM sys.indexes 
        WHERE name = 'IX_' + @table_name + '_' + COLUMN_NAME 
        AND object_id = OBJECT_ID(@table_name)
    )
    THEN 'CREATE INDEX IX_' + @table_name + '_' + COLUMN_NAME + ' ON ' + 
         QUOTENAME(@table_name) + '(' + QUOTENAME(COLUMN_NAME) + ');' + CHAR(13) +
         'PRINT ''索引IX_' + @table_name + '_' + COLUMN_NAME + '创建成功'';' + CHAR(13)
    ELSE 'PRINT ''索引IX_' + @table_name + '_' + COLUMN_NAME + '已存在'';' + CHAR(13)
    END
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = @table_name
AND COLUMN_NAME LIKE '%ID';

EXEC sp_executesql @sql;
GO

-- 验证索引创建结果
SELECT 
    i.name AS 索引名称,
    COL_NAME(ic.object_id, ic.column_id) AS 字段名
FROM sys.indexes i
INNER JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
WHERE i.object_id = OBJECT_ID('T_PLN_RESERVEBILL')
ORDER BY i.name;
GO

COMMIT TRANSACTION;
GO
