不使用SQL Query中的值替换@TFYID变量

时间:2017-07-08 09:39:26

标签: sql sql-server sql-server-2008

set @TFYID=7
print @TFYID

set @SQL =N'select @ETotal=sum(ExemptionProduce) 
            from   tbl_Income_Exemption 
            where  EmployeeID='''+@EmpID+'''  and (TDSSettingsDetailID) in 
                  ('+@ConcatString+''') and FinancialYearID='+@TFYID+''

exec sp_executesql @SQL

输出:

7
Msg 245, Level 16, State 1, Line 73
Conversion failed when converting the nvarchar value '
select @ETotal=sum(ExemptionProduce) 
from   tbl_Income_Exemption 
where  EmployeeID='00402060'  and (TDSSettingsDetailID) in 
       ('24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36') 
       and FinancialYearID=' to data type int.

此查询未显示正确输出。 它给了我一些错误。 请帮助我。

1 个答案:

答案 0 :(得分:0)

编写查询所需的方法是将值转换为字符串:

set @SQL =N'select @ETotal=sum(ExemptionProduce) 
            from   tbl_Income_Exemption 
            where  EmployeeID='''+cast(@EmpID as varchar(255))+'''  and (TDSSettingsDetailID) in 
                  ('+@ConcatString+''') and FinancialYearID='+cast(@TFYID as varchar(255))+''

exec sp_executesql @SQL

但是,编写查询的正确方法是使用参数 - 至少在哪里可以:

declare @ETotal decimal(18, 4);  -- or whatever

set @SQL = N'
select @ETotal = sum(ExemptionProduce) 
from tbl_Income_Exemption 
where EmployeeID = @EmpID and
      TDSSettingsDetailID in (' + @ConcatString + ') and 
      FinancialYearID = @TFYID';

exec sp_executesql @SQL,
     N'@ETotal decimal(18, 4) output, @EmpId int, @TFYID int',
     @ETotal = @ETotal output, @EmpId = @EmpId, @TFYID = @TFYID;

您无法将in列表作为单个参数传递,因此更改查询字符串是一个可行的选项。

这是否有效取决于您在问题中未解释的事物的价值和类型。但是你应该能够得到正确的想法。