Since you want to use that variable.
Then best split the letters or words.
Having the STRING_SPLIT function would be great for this.
But there are more ways to split strings.
The example below does it with a WHILE
loop.
CREATE TABLE [Table]
( id INT IDENTITY(101,1) PRIMARY KEY,
name NVARCHAR(100) NOT NULL
);
GO
✓
INSERT INTO [Table] (name) VALUES
('a munchkin'),
('never ever sever mah lever'),
('saintess'),
('them mammaries');
GO
4 rows affected
DECLARE @value NVARCHAR(1000);
SET @value =' m n ';
DECLARE @values TABLE (
value NVARCHAR(42)
);
DECLARE @words NVARCHAR(1000);
DECLARE @word NVARCHAR(42);
SET @words = RTRIM(LTRIM(@value))+' ';
WHILE CHARINDEX(' ', @words) > 0
BEGIN
SET @word = SUBSTRING(@words,0,CHARINDEX(' ',@words))
SET @words = LTRIM(SUBSTRING(@words,CHARINDEX(' ',@words)+1,LEN(@words)))
IF @word != '' INSERT INTO @values (value) VALUES (@word);
END;
DECLARE @TotalValues INT;
SET @TotalValues = (select count(distinct value) from @values);
--
-- use the table variable to query the table
--
SELECT *
FROM [Table] t
WHERE EXISTS
(
SELECT 1
FROM @values v
WHERE t.name LIKE '%'+v.value+'%'
HAVING COUNT(DISTINCT v.value) = @TotalValues
);
GO
id | name
--: | :-------------------------
101 | a munchkin
102 | never ever sever mah lever
db<>fiddle here