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