简体   繁体   中英

How to index only columns of type nvarchar in the table in SQL Server?

I am working on creating trigger to index columns of type nvarchar in a table in SQL Server dynamically. ie I need to index only those columns in the table if the column type is nvarchar . How to do it?

You can do this with dynamic sql and a cursor:

declare @IndexSQL as nvarchar(max)
declare mycursor cursor for 
select  'CREATE NONCLUSTERED INDEX [IX_' + ta.name + '_' + c.name + '] ON [dbo].[MyTableName] ([' + c.name + '] ASC); ' as [IndexSQL]
from sys.columns c
inner join sys.types ty on ty.user_type_id = c.user_type_id
inner join sys.tables ta on c.object_id = ta.object_id
where ta.name = '[MyTableName]' and ty.name = 'nvarchar'
open mycursor
fetch next from mycursor into @IndexSQL
while @@FETCH_STATUS=0
    begin
    exec(@IndexSQL)
    fetch next from mycursor into @IndexSQL
    end
close mycursor
deallocate mycursor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM