I am building a string for the rest of my sql query
to be run by
EXEC fuction on my SP
I am having trouble creating this string
WHERE (FullName LIKE '%[1STFullNameSearchValue]%' OR FullName LIKE '%[2ndFullNameSearchValue]%') AND (DepartmentName LIKE '%[1stDepartmentNameSearchValue]%' OR DepartmentName LIKE '%[2ndDepartmentNameSearchValue]%')
given this
CREATE TYPE [dbo].[SearchField] AS TABLE(
[FieldName] [NVARCHAR](50) NULL,
[SearchValue] [NVARCHAR](50) NULL
)
DECLARE @SearchFields AS SearchField;
insert into @SearchFields values('FullName', 'John')
insert into @SearchFields values('FullName', 'Karl')
insert into @SearchFields values('DepartmentName', 'Accounting')
insert into @SearchFields values('DepartmentName', 'Billing')
Expected Result
WHERE (FullName LIKE '%John%' OR FullName LIKE '%Karl%') AND (DepartmentName LIKE '%Accounting%' OR DepartmentName LIKE '%Billing%')
This is what I have
;WITH cte_like
(
SELECT
GroupNum = CONCAT('(',STRING_AGG(CONCAT('%',SF.SearchValue,'%'),CONCAT(' OR ',SF.FieldName,' LIKE ')),')')
FROM
@SearchFields SF
GROUP BY SF.FieldName
)
SELECT SearchCriteria FROM cte_grouped
whereClause AS (
SELECT
SearchCriteria = CONCAT('(',SF.FieldName, ' LIKE ' , QUOTENAME(CONCAT('%',SearchValue,'%'),''''),' OR '')')
FROM
@SearchFields SF
GROUP BY SF.FieldName
)
select @nSQLWhere = 'WHERE ' + STRING_AGG(SearchCriteria, ' AND ')
from cte_where;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…