我想创建一个SQL命令来创建一个带条件的索引。 索引所基于的列以及过滤器表达式中使用的列都可能不存在 所以我添加了一个条件,两列都存在,但我仍然得到过滤器表达式中列的无效列名称错误。 有办法解决这个问题吗?
IF EXISTS (SELECT 1
FROM sys.all_columns
WHERE name='Field1'
AND object_id=OBJECT_ID('[dbo].[Table1]') )
AND EXISTS (SELECT 1
FROM sys.all_columns
WHERE name='Field2'
AND object_id=OBJECT_ID('[dbo].[Table1]') )
BEGIN
CREATE NONCLUSTERED INDEX [IX_Table1_Field1] ON [dbo].[Table1]
(
[Field1]
)
WHERE ([Field2]=(1))
END
出现问题的表
CREATE TABLE [dbo].[Table1] (
[Field1] [int]
)
答案 0 :(得分:1)
如果我理解你真正想要的东西,我认为你需要像这样使用动态SQL:
declare @tableName nvarchar(max) = N'Table2', @field1 nvarchar(max) = N'Field1', @field2 nvarchar(max) = N'Field2';
declare @sql nvarchar(max) = '';
if exists (select 1
from sys.all_columns
where name = @field1
and [object_id] = object_id(@tableName))
and exists (select 1
from sys.all_columns
where name = @field2
and [object_id] = object_id(@tableName))
begin
set @sql = 'create nonclustered index [IX_'+@tableName+'_'+@field1+'] on [dbo].['+@tableName+'] ( ['+@field1+']) where ['+@field2+']= 1';
end
else if exists (select 1
from sys.all_columns
where name = @field1
and [object_id] = object_id(@tableName))
begin
set @sql = 'create nonclustered index [IX_'+@tableName+'_'+@field1+'] on [dbo].['+@tableName+'] ( ['+@field1+'])';
end
else if exists (select 1
from sys.all_columns
where name = @field2
and [object_id] = object_id(@tableName))
begin
set @sql = 'create nonclustered index [IX_'+@tableName+'_'+@field2+'] on [dbo].['+@tableName+'] ( ['+@field2+'])';
end
exec sp_sqlexec @sql;
go