我只是尝试使用while循环构建查询,并按如下方式检查数据类型。
为了便于理解,我在查询本身中添加了注释。
待办事项
:
1-您需要在下面的查询中添加其他数据类型。
2-需要参数化查询并使用
sp_executesql
SQL注入攻击
--Table to Store search inputs, which will be your table type parameter.
DECLARE @v TABLE (searchString VARCHAR(100))
--Sample Inputs
INSERT INTO @v
SELECT *
FROM (
VALUES ('smith')
,('1234')
,('london')
,('12/01/2020')
) t(v)
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
--Create a temporary table to loop the serach inputs
SELECT *
,0 AS IsProcessed
INTO #Temp
FROM @v
DECLARE @query NVARCHAR(max) = 'SELECT * FROM customersview WHERE 1 = 1 '
DECLARE @searchString VARCHAR(100)
--Loop through each search input
WHILE (
SELECT Count(*)
FROM #Temp
) > 0
BEGIN
SELECT TOP 1 @searchString = searchString
FROM #Temp
SELECT @searchString
--Check if input is int/bigint type
IF (ISNUMERIC(@searchString) = 1)
BEGIN
SET @query = @query + 'AND ' + @searchString + ' IN (' + Stuff((
SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
FROM (
SELECT COLUMN_NAME
,DATA_TYPE
FROM INFORMATION_SCHEMA.VIEWS v
JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
AND c.TABLE_NAME = v.TABLE_NAME
WHERE c.TABLE_NAME = 'customersview'
AND DATA_TYPE IN ('int', 'bigint')
) t
FOR XML path('')
,type
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
END
--Check if input is date type
ELSE IF (ISDATE(@searchString) = 1)
BEGIN
SET @query = @query + ' AND ''' + @searchString + ''' IN (' + Stuff((
SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
FROM (
SELECT COLUMN_NAME
,DATA_TYPE
FROM INFORMATION_SCHEMA.VIEWS v
JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
AND c.TABLE_NAME = v.TABLE_NAME
WHERE c.TABLE_NAME = 'customersview'
AND DATA_TYPE IN ('date', 'datetime')
) t
FOR XML path('')
,type
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
END
ELSE
BEGIN
--Check if input is VARCHAR/NVARCHAR type
SET @query = @query + ' AND ''' + @searchString + ''' IN (' + Stuff((
SELECT DISTINCT ', ' + Quotename(COLUMN_NAME)
FROM (
SELECT COLUMN_NAME
,DATA_TYPE
FROM INFORMATION_SCHEMA.VIEWS v
JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_SCHEMA = v.TABLE_SCHEMA
AND c.TABLE_NAME = v.TABLE_NAME
WHERE c.TABLE_NAME = 'customersview'
AND DATA_TYPE IN ('VARCHAR', 'NVARCHAR')
) t
FOR XML path('')
,type
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ')'
END
DELETE #Temp
WHERE searchString = @searchString
END
SELECT @query
--Execute the query
--EXEC(@Query)