将数据类型varchar转换为numeric和overflow时出错

时间:2018-05-24 13:50:20

标签: sql sql-server

declare @Commission decimal(18,2)
select @Commission=percentage from Commission
declare @qry varchar(Max)

set @qry='select 5 +'+@Commission +''

EXEC(@qry)

这里

  

将数据类型varchar转换为数字时出错。

5 个答案:

答案 0 :(得分:2)

不要将值作为字符串传递给动态SQL。相反,请学会使用sp_executesql

declare @Commission decimal(18, 2);

select @Commission = percentage
from Commission;

declare @qry varchar(Max);

set @qry='select 5 + @Commission';

exec sp_executesql @qry, 'N@Commission decimal(18, 2)', @Commission=@Commission;

答案 1 :(得分:0)

set @qry='select 5 +'+convert(nvarchar(max),@FranchiseeCommission)+''

答案 2 :(得分:0)

试试这样:

SET @qry='select 5 +'+CAST(@FranchiseeCommission AS varchar(30))+''

由于您的变量是小数,因此必须将其转换为varchar才能将其与字符串组合。

答案 3 :(得分:0)

SQL Server的隐式转换规则使其尝试将varchar隐式转换为decimal。您需要明确地将decimal转换为varchar

set @qry='select 5 +'+ CAST(@FranchiseeCommission as varchar(20))

答案 4 :(得分:0)

如果2012 +

,总会有concat()
set @qry=concat('select 5 +',@Commission)