如何在SQL Server的表中仅索引nvarchar类型的列?

时间:2018-07-06 13:49:17

标签: sql sql-server

我正在努力创建触发器来动态索引SQL Server表中类型nvarchar的列。即,如果列类型为nvarchar,则只需要索引表中的那些列。怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用动态sql和游标执行此操作:

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