You might find yourself in a situation where you have to analyze the indexes for a given table and want to know which columns are part of which index. Such a view can help you quickly analyze which indexes are reduntant and can probably be dropped.
Use the below code to accomplish that. This code gives you the result set as mentioned below:
1. Rows as the list of indexes.
2. Columns as the list of columns in that table
3. Result set in each row displays 1 for each column that is included in that index, else displays 0
DECLARE @Columns NVARCHAR(MAX), @SQL NVARCHAR(MAX);
-- Step 1: Construct the list of columns for the dbo.Associate table using FOR XML PATH
SELECT @Columns = STUFF((
SELECT ', MAX(CASE WHEN c.name = ''' + c.name + ''' THEN 1 ELSE 0 END) AS ' + QUOTENAME(c.name)
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE t.name = 'TABLENAME' AND t.schema_id = SCHEMA_ID('dbo') --Replace TABLENAME here
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '');
-- Step 2: Construct the dynamic SQL query
SET @SQL = '
SELECT
i.name AS IndexName, ' + @Columns + '
FROM
sys.indexes i
JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id
JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id
JOIN sys.tables t ON t.object_id = i.object_id
WHERE
t.name = ''Associate'' AND t.schema_id = SCHEMA_ID(''dbo'')
GROUP BY
i.name
ORDER BY
i.name';
-- Step 3: Execute the dynamic SQL query
EXEC sp_executesql @SQL;
I found this blog to be extremely useful and engaging. The way you explained the topic is clear, well-structured, and easy for readers of all experience levels to understand. I appreciate the effort you put into sharing practical information instead of just basic facts. Your writing style keeps the reader interested from beginning to end, and the examples make the content even more valuable. Articles like this help people gain knowledge and confidence while learning something new. Thank you for sharing such high-quality content with your audience. I will definitely recommend this blog to others who are interested in this topic and look forward to reading more informative posts from you. Keep publishing such excellent and helpful articles!
ReplyDeleteBest Fashion Designing institute in Delhi NCR
Art & Craft Institute in Delhi
business analytics course in delhi ncr