我正在尝试在“名称”列上的基于参数的过滤器存储过程中使用通配符搜索,但我尝试过的所有操作要么得到:模运算符中的数据类型nvarchar和varchar不兼容-或编译时不兼容我最终遇到了不正确的语法错误。
DECLARE @sql nvarchar(max) = N'
SELECT *
FROM MyTable
WHERE 1 = 1'
+ CASE WHEN @Name IS NOT NULL THEN
N' AND NAME LIKE '%' + @Name + '%'' ELSE N'' END
+ CASE WHEN @AccountNumber IS NOT NULL THEN
N' AND ACCOUNT_NO LIKE @AccountNumber' ELSE N'' END
DECLARE @params nvarchar(max) = N'
@Name varchar (20)
,@AccountNumber varchar(15)';
EXEC sys.sp_executesql @sql, @params,
@Name,
@AccountNumber;
答案 0 :(得分:0)
非常确定您可以跳过动态sql并执行类似的操作。
SELECT *
FROM MyTable
WHERE NAME LIKE '%' + @Name + '%' --no need to check if the parameter is NULL, if it is this will not return anything.
OR ACCOUNT_NO = @AccountNumber --used equality here since you had no wildcard
答案 1 :(得分:0)
沿着动态SQL路线,您可以执行以下操作:
DECLARE @Name varchar(10), @AccountNumber int;
--SET @Name = 'Smith';
--SET @AccountNumber = 12345;
DECLARE @SQL nvarchar(MAX);
SET @SQL = N'SELECT *' + NCHAR(13) + NCHAR(10) +
N'FROM MyTable' +
CASE WHEN @Name IS NOT NULL OR @AccountNumber IS NOT NULL THEN NCHAR(13) + NCHAR(10) + N'WHERE ' ELSE N'' END +
ISNULL(STUFF(CASE WHEN @Name IS NOT NULL THEN NCHAR(13) + NCHAR(10) + N' AND NAME LIKE ''%'' + @Name + ''%''' ELSE N'' END +
CASE WHEN @AccountNumber IS NOT NULL THEN NCHAR(13) + NCHAR(10) + N' AND ACCOUNT_NO = @AccountNumber' ELSE N'' END,1,8,N''),N'') + N';';
PRINT @SQL;
--EXEC sp_executesql @SQL,N'@Name varchar(10), @AccountNumber int', @Name = @Name, @AccountNumber = @AccountNumber;
像肖恩一样,我怀疑这需要动态查询,但也许我们有一个过于简单的陈述?谁知道。上面的内容(如果您取消注释SET
语句)将返回以下语句之一:
SELECT *
FROM MyTable;
SELECT *
FROM MyTable
WHERE NAME LIKE '%' + @Name + '%';
SELECT *
FROM MyTable
WHERE ACCOUNT_NO = @AccountNumber;
SELECT *
FROM MyTable
WHERE NAME LIKE '%' + @Name + '%'
AND ACCOUNT_NO = @AccountNumber;
答案 2 :(得分:0)
仅在混合中添加另一个选项,我们就可以使用此选项进行全部捕获查询。
org.apache.kafka.connect.transforms.*
最后一部分对于获得最佳执行计划很重要。