For wide character columns your best bet is to calculate a checksum and add an index.
Then calculate the checksum of what you are searching for and add that to your query, it looks like this:
-- add a persisted computed column, we will calculate a checksum over the body column which is of type nvarchar(max)
alter table dbo.posts add chksum_body as checksum(body) persisted
-- add an nonclustered index to the table for the new column
create nonclustered index ncix_posts_chksum_body on dbo.posts (chksum_body)
-- show query io and cpu usage
set statistics io, time on
-- we need 2 variables, one for the string we are searching for and one for its checksum
declare @str nvarchar(max)
declare @chksumstr int
-- initialise the variable with the search string
select @str = N'Can anyone help me to index wide columns in SQL Server please'
-- calculate a checksum for the search string and store in a variable
select @chksumstr = checksum(@str)
-- compare search the old way (no index)
select top 100 * from [dbo].[Posts] where body = N'Can anyone help me to index wide columns in SQL Server please'
-- to search using the checksum, note we recheck the value of the body to eliminate any false matches due to checksum collisions
-- but as we have an index seek we just are doing a residual filter on the few matching rows
select top 100 * from [dbo].[Posts] where body = @str and chksum_body = @chksumstr
SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms.
Id AcceptedAnswerId AnswerCount Body
72 0 2 Can anyone help me to index wide columns in SQL Server please
(1 row affected)
Table 'Posts'. Scan count 5, logical reads 4239877, physical reads 2150, page server reads 0, read-ahead reads 4194084, page server read-ahead reads 0, lob logical reads 677199, lob physical reads 407176, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0. Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.
SQL Server Execution Times: CPU time = 34829 ms, elapsed time = 36995 ms.
Id AcceptedAnswerId AnswerCount Body
72 0 2 Can anyone help me to index wide columns in SQL Server please
(1 row affected)
Table 'Posts'. Scan count 1, logical reads 7, physical reads 4, page server reads 0, read-ahead reads 0, page server read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob page server reads 0, lob read-ahead reads 0, lob page server read-ahead reads 0.
SQL Server Execution Times: CPU time = 0 ms, elapsed time = 0 ms.
varchar(max)
column; does it really have no practical limit? See here.