我正在尝试为我的应用程序实现高级搜索功能,其中我在以下结构中有SQL
表值参数,
ColumnName Operator Keyword
------------------------------------
Name StartsWith Ram
City Equals Chennai
我的SQL
表格,
Name City CreatedDate
-----------------------------------
Ram Chennai 10/10/2014
Ramachan Kovai 02/03/2015
我如何循环遍历此TVP
以便我可以构建WHERE
子句并将其附加到SELECT
查询,这更快,因为我有10行搜索值(标准)。
过滤器与AND
运营商关联。
使用的运营商名单:
答案 0 :(得分:1)
您可以创建如下所示的动态过滤表达式,并在SQL中使用它。在TVP中添加编辑过滤器并根据各自的数据类型进行验证时,您需要非常小心
使用数据创建类型和基表
/*
CREATE TYPE FilterTVP AS TABLE
(
ColumnName VARCHAR(30), Operator VARCHAR(30), Keyword VARCHAR(30)
);
GO
CREATE TABLE myTable
(
Name VARCHAR(50),
City VARCHAR(50),
CreatedDate DATE
)
INSERT INTO myTable VALUES('Ram','Chennai','10/10/2014'),('Ramachan','Kovai','02/03/2015')
*/
<强>查询强>
DECLARE @Param FilterTVP
INSERT INTO @Param VALUES('Name','StartsWith','Ram'),('City','Equals','Chennai'),('CreatedDate','From','2014-05-05')
DECLARE @FilterExp NVARCHAR(MAX)
SELECT @FilterExp =
(SELECT
' AND ' + QUOTENAME(ColumnName,'[') + ' ' +
CASE Operator
WHEN 'Equals'
THEN '='
WHEN 'Not equals'
THEN '<>'
WHEN 'StartsWith'
THEN 'LIKE'
WHEN 'Endswith'
THEN 'LIKE'
WHEN 'From'
THEN '>='
WHEN 'To'
THEN '<='
END + ' ' +
CASE
WHEN Operator = 'Startswith' THEN QUOTENAME(Keyword + '%','''')
WHEN Operator = 'Endswith' THEN QUOTENAME('%' + Keyword ,'''')
ELSE QUOTENAME(Keyword,'''')
END
FROM @Param
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)')
SET @FilterExp = 'SELECT * FROM myTable WHERE 1=1 ' + ISNULL(@FilterExp,'')
PRINT @FilterExp
EXEC sp_executeSQL @FilterExp
<强>输出强>
Name City CreatedDate
--------------------------
Ram Chennai 2014-10-10
答案 1 :(得分:0)
构建语句然后执行它,例如:
CREATE TABLE f
(
ColumnName NVARCHAR(MAX) ,
Operator NVARCHAR(MAX) ,
KeyWord NVARCHAR(MAX)
)
CREATE TABLE t
(
Name NVARCHAR(MAX) ,
City NVARCHAR(MAX)
)
INSERT INTO f
VALUES ( 'Name', 'StartsWith', 'Ram' ),
( 'City', 'Equals', 'Chennai' )
INSERT INTO t
VALUES ( 'Ram', 'Chennai' ),
( 'Ramachan', 'Kovai' )
DECLARE @op NVARCHAR(MAX) ,
@v NVARCHAR(MAX)
DECLARE @statement NVARCHAR(MAX) = 'SELECT * FROM t WHERE Name '
SELECT @op = Operator ,
@v = KeyWord
FROM f
WHERE ColumnName = 'Name'
SET @statement = @statement + CASE @op
WHEN 'StartsWith' THEN 'LIKE ''' + @v + '%'''
ELSE ' = ''' + @v + ''''
END + ' AND City'
SELECT @op = Operator ,
@v = KeyWord
FROM f
WHERE ColumnName = 'City'
SET @statement = @statement + CASE @op
WHEN 'StartsWith' THEN 'LIKE ''%' + @v + '%'''
ELSE ' = ''' + @v + ''''
END
EXEC(@statement)
输出:
Name City
Ram Chennai