Modifying the Existing Code to Accept a Multi-Term Search Value without Creating a Table
If you can't create a table, you can pass the search terms as a comma-separated string and then split them into individual terms using a string splitting function. Here's an updated version of the code:
-- Dynamic Velcro
DECLARE @TableName NVARCHAR(128) = 'table_one';
DECLARE @SchemaName NVARCHAR(128) = 'dbo';
DECLARE @SearchValue NVARCHAR(MAX) = 'squirrel,fox,rabbit';
DECLARE @SQL NVARCHAR(MAX) = '';
-- Split the search terms into individual terms
WITH SearchTerms AS (
SELECT value AS SearchTerm
FROM STRING_SPLIT(@SearchValue, ',')
WHERE LTRIM(RTRIM(value)) <> ''
)
-- Generate the dynamic SQL
SELECT @SQL = STRING_AGG(
CAST(
'(' +
STRING_AGG(
QUOTENAME(c.name) + ' LIKE ''%' + st.SearchTerm + '%''',
' OR '
) +
')'
AS NVARCHAR(MAX)
),
' OR '
)
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.schemas s ON t.schema_id = s.schema_id
CROSS JOIN SearchTerms st
WHERE t.name = @TableName
AND s.name = @SchemaName
AND c.system_type_id IN (167, 175, 231, 239); -- char, varchar, nchar, nvarchar
-- If no columns are found, @SQL will be NULL, so we need to handle this case
IF @SQL IS NULL
BEGIN
SET @SQL = 'SELECT * FROM ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) + ' WHERE 1 = 0';
END
ELSE
BEGIN
SET @SQL = 'SELECT * FROM ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@TableName) +
' WHERE ' + @SQL;
END
-- Print or execute the dynamic SQL
PRINT @SQL;
--EXEC sp_executesql @SQL;
How the Code Works
- We pass the search terms as a comma-separated string in the
@SearchValue variable.
- We use a Common Table Expression (CTE) to split the
@SearchValue into individual terms using the STRING_SPLIT function.
- We use a
CROSS JOIN to join the SearchTerms CTE with the sys.columns table, so that we generate a condition for each column and each search term.
- The rest of the code is the same as before.
Note
The STRING_SPLIT function is available in SQL Server 2016 and later versions. If you're using an earlier version, you can use a different string splitting function, such as a CLR function or a custom T-SQL function.
Alternative for Earlier Versions
If you're using an earlier version of SQL Server that doesn't support STRING_SPLIT, you can use a custom T-SQL function to split the string. Here's an example:
CREATE FUNCTION dbo.SplitString (@str nvarchar(max), @delimiter nvarchar(10))
RETURNS @result TABLE (value nvarchar(max))
AS
BEGIN
DECLARE @pos int;
WHILE CHARINDEX(@delimiter, @str) > 0
BEGIN
SET @pos = CHARINDEX(@delimiter, @str);
INSERT INTO @result (value) VALUES (LTRIM(RTRIM(LEFT(@str, @pos - 1))));
SET @str = LTRIM(RTRIM(RIGHT(@str, LEN(@str) - @pos)));
END
IF LEN(@str) > 0
BEGIN
INSERT INTO @result (value) VALUES (LTRIM(RTRIM(@str)));
END
RETURN;
END
GO