简体   繁体   English

将nvarchar值转换为数据类型int时转换失败

[英]Conversion failed while converting nvarchar value to datatype int

I want to get the values of @sql to p. 我想获取@sql的值到p。 But while conversion it says that "Conversion failed when converting the nvarchar value 'select sum(stock) from[Hard disk]' to data type int." 但是在转换时,它表示“将nvarchar值'select sum(stock)从[硬盘]转换为数据类型int时转换失败。”

declare @tname varchar(10);
declare @p int
declare @i int

declare @sql nvarchar(max);

set @tname = 'Hard disk';

set @sql = 'select sum(stock) from' + '[' + @tname + ']'

exec  (@sql)

print @sql

select @p = convert(int,@sql)

print @p

What i want is to assign the result of the query @SQL in integer variable @p.. 我想要的是在整数变量@p中分配查询@SQL的结果。

One way to do it is do it all in the dynamic sql. 一种方法是在动态sql中完成所有操作。

declare @tname varchar(10);
declare @p int
declare @i int

declare @sql nvarchar(max);

set @tname = 'Hard disk';

set @sql = 
'DECLARE @Result AS INT
select @Result = sum(stock) from' + '[' + @tname + ']
PRINT @Result'

exec  (@sql)

The other way would be creating an output param. 另一种方法是创建输出参数。

DECLARE @tname VARCHAR(50)
DECLARE @SQLString NVARCHAR(500)
DECLARE @ParmDefinition NVARCHAR(500)
DECLARE @Result INT

SET @tname = 'Hard disk';
SET @SQLString = N'SELECT @Result = sum(stock)
                   FROM ' + QUOTENAME( @tname )  
SET @ParmDefinition = N'@Result INT OUTPUT'
EXECUTE sp_executesql
@SQLString,
@ParmDefinition,
@Result=@Result OUTPUT

PRINT @Result

You better use QUOTENAME for embrasing the table name with the brackets, as it is more native. 最好使用QUOTENAME将表名括在方括号中,因为它更原始。

declare @p int;
EXEC SP_EXECUTESQL N'select @p = sum(stock) from '[' + @tname + ']',N'@p int OUTPUT',@p    OUTPUT;
select @p

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将nvarchar值转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value to datatype int 在排序时将nvarchar值“XX”转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value “XX” to data type int while sorting 将nvarchar值“第1部分”转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value 'Part 1' to data type int 将 nvarchar 值“....”转换为数据类型 int 时转换失败 - Conversion failed when converting the nvarchar value '....' to data type int 将nvarchar值'OrgID'转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value 'OrgID' to data type int 将nvarchar值'S'转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value 'S' to data type int 将nvarchar值'undefined'转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value ' undefined' to data type int 将nvarchar值“ meetingId”转换为数据类型int时转换失败 - Conversion failed when converting the nvarchar value 'meetingId' to data type int 将 nvarchar 值 '' 转换为数据类型 int 时转换失败 - Conversion failed when converting the nvarchar value '' to data type int 将 nvarchar 值...转换为数据类型 int 时转换失败 - Conversion failed when converting the nvarchar value ... to data type int
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM