如何对指定的列名和值使用LIKE操作

时间:2018-07-25 06:06:39

标签: sql sql-server sql-like

如何使用类似的操作仅在指定的列上进行搜索

示例代码无效

DECLARE @COL_NAME VARCHAR(30) = 'EMAIL'
DECLARE @COL_VALUE VARCHAR(100) = 'xyz@so.com'

SELECT * FROM SOMETABLE
WHERE COLUMN_NAME = @COL_NAME AND 'COL_NAME' LIKE '%' + @COL_VALUE + '%'

2 个答案:

答案 0 :(得分:3)

我将使用参数化的SQL,并将@COL_NAME包裹在QUOTENAME()中,以防止SQL注入:

DECLARE @SQL NVARCHAR(MAX);
DECLARE @COL_NAME sysname = 'EMAIL'
DECLARE @COL_VALUE VARCHAR(100) = 'xyz@so.com'

SET @SQL = N'
    SELECT *
    FROM SOMETABLE
    WHERE ' + QUOTENAME(@COL_NAME) + ' LIKE ''%@COL_VALUE%''';

EXECUTE sp_executesql @SQL, N'@COL_VALUE VARCHAR(100)', @COL_VALUE = @COL_VALUE;

答案 1 :(得分:1)

您需要转义文字单引号。一种方法是将它们加倍:

DECLARE @COL_NAME VARCHAR(30) = 'EMAIL'
DECLARE @COL_VALUE VARCHAR(100) = 'xyz@so.com'

EXEC ('SELECT * FROM SOMETABLE
WHERE ' + @COL_NAME + ' LIKE ''%' + @COL_VALUE + '%''')