sql server - SQL filtered index when the column in the filtered expression is possible not present? -




i want create sql command create index condition. both columns on index based column used in filter expression possible not present.
added condition both columns present still invalid column name error column in filter expression. there way around this?

if exists (select 1         sys.all_columns         name='field1'         , object_id=object_id('[dbo].[table1]') ) , exists (select 1         sys.all_columns         name='field2'         , object_id=object_id('[dbo].[table1]') )  begin  create nonclustered index [ix_table1_field1] on [dbo].[table1] (     [field1] )  ([field2]=(1))  end 

table problem occurs

create table [dbo].[table1] (      [field1] [int]  ) 

if understand want, think need use dynamic sql this:

declare @tablename nvarchar(max) = n'table2', @field1 nvarchar(max) = n'field1', @field2 nvarchar(max) = n'field2'; declare @sql nvarchar(max) = '';  if exists (select 1         sys.all_columns        name = @field1        , [object_id] = object_id(@tablename)) , exists (select 1         sys.all_columns        name = @field2        , [object_id] = object_id(@tablename)) begin     set @sql = 'create nonclustered index [ix_'+@tablename+'_'+@field1+'] on [dbo].['+@tablename+'] ( ['+@field1+']) ['+@field2+']= 1'; end else if exists (select 1         sys.all_columns        name = @field1        , [object_id] = object_id(@tablename)) begin     set @sql = 'create nonclustered index [ix_'+@tablename+'_'+@field1+'] on [dbo].['+@tablename+'] ( ['+@field1+'])'; end else if exists (select 1         sys.all_columns        name = @field2        , [object_id] = object_id(@tablename)) begin     set @sql = 'create nonclustered index [ix_'+@tablename+'_'+@field2+'] on [dbo].['+@tablename+'] ( ['+@field2+'])'; end  exec sp_sqlexec @sql; go 




wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -