[英]Conversion failed when converting the varchar value '%' to data type int Error
I have this query that is based on a @Amount
parameter 我有基于
@Amount
参数的此查询
Amount varchar(20)= NULL
SELECT .....
Format(T1.Amount, 'c', 'en-us') as Amount1,
Format(T2.Amount, 'c', 'en-us') as Amount2
FROM Table1
WHERE .....
AND (T1.Amount>= CAST(@Amount AS INT) OR T2.Amount >= CAST(@Amount AS INT))
AND @Amount IS NOT NULL
If the @Amount
parameter is not NULL
and is numeric the query works perfectly, but if the @Amount
parameter is '%'
or NULL
I get the above conversion error. 如果
@Amount
参数不为NULL
且为数字,则查询可正常运行,但是如果@Amount
参数为'%'
或NULL
, @Amount
出现上述转换错误。
Any idea on how to solve that? 有什么解决办法的想法吗?
Simple approach to check if the value is numeric: 检查值是否为数字的简单方法:
DECLARE @Amount VARCHAR(20)= '23';
IF ISNUMERIC(@Amount) = 0
BEGIN
PRINT 'Amount is null or is not a number';
END;
ELSE
BEGIN
PRINT 'Amount: ' + @Amount;
END;
To do it in the WHERE
clause: 要在
WHERE
子句中执行此操作:
DECLARE @Amount VARCHAR(20)= '23';
SELECT 'Some Data' AS Result
WHERE ISNUMERIC(@Amount) = 1 AND @Amount > 0
Why don't you use the proper int
type for the @Amount
parameter? 为什么不对
@Amount
参数使用正确的int
类型? Why do you use varchar
? 为什么使用
varchar
?
I would make the type of the @Amount
parameter int
and pass actual value or NULL
. 我将把
@Amount
参数的类型@Amount
int
并传递实际值或NULL
。 Passing NULL
would indicate that this parameter should be ignored. 传递
NULL
将指示应忽略此参数。
@Amount int = NULL
SELECT .....
Format(T1.Amount, 'c', 'en-us') as Amount1,
Format(T2.Amount, 'c', 'en-us') as Amount2
FROM
T1 ... JOIN T2 ...
WHERE
.....
AND (@Amount IS NULL OR T1.Amount >= @Amount OR T2.Amount >= @Amount)
OPTION (RECOMPILE)
This type of the query is called Dynamic Search Condition . 这种查询称为动态搜索条件 。 I recommend to read this article by Erland Sommarskog for detailed explanations and why
OPTION (RECOMPILE)
is important for this type of queries. 我建议阅读Erland Sommarskog的这篇文章,以获取详细说明以及为什么
OPTION (RECOMPILE)
对于此类查询很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.