【问题标题】:"Conversion failed when converting the nvarchar value '113332,113347' to data type int." [duplicate]“将 nvarchar 值 '113332,113347' 转换为数据类型 int 时转换失败。” [复制]
【发布时间】:2016-09-02 19:18:25
【问题描述】:

我收到以下代码的错误。我将本地 ID 传递为“113332,113347”

cn.Open();
SqlCommand cmd = new SqlCommand("SelectUser", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@in_UserId", SqlDbType.Int).Value = Convert.ToInt32(userId);
cmd.Parameters.Add("@in_StartDate", SqlDbType.DateTime).Value = fromDate;
cmd.Parameters.Add("@in_EndDate", SqlDbType.DateTime).Value = toDate;
cmd.Parameters.Add("@in_LocalIds", SqlDbType.NVarChar, 100).Value = localids.ToString();
cmd.ExecuteNonQuery();

“将 nvarchar 值 '113332,113347' 转换为数据类型 int 时转换失败。”

在数据库中,本地id的数据类型是int。

存储过程代码如下

CREATE PROCEDURE [dbo].[User_Update] @in_UserId INT
,@in_StartDate DATETIME
,@in_EndDate DATETIME
,@in_LocalIds NVARCHAR(100)
AS
BEGIN
SELECT * FROM TABLE1 WHERE LocalId in (@in_LocalIds) AND UserId = @in_UserId
END
go

【问题讨论】:

  • 那么当它失败时,userId 中的内容是什么?看起来它不是一个 int。
  • 你能发布存储过程吗?还有你的代码中的localids是什么类型?
  • 听起来你有一个错误,并且你将相同的字符串值“113332,113347”分配给localidsuserid
  • 这不是错误,您不能像这样参数化查询的IN() 部分。

标签: c# ado.net


【解决方案1】:

@in_LocalIds 参数中,int 由 ',' 连接,因此拆分值(在 SQL 中应该是某种 while 循环),将值转换为 int 并将它们插入到临时表中。

然后在 where 子句中使用该表。

编辑:

CREATE PROCEDURE [dbo].[User_Update] @in_UserId INT
,@in_StartDate DATETIME
,@in_EndDate DATETIME
,@in_LocalIds NVARCHAR(100)
AS
BEGIN

declare @tempLocalIds nvarchar(100)
declare @tempStrId nvarchar(100)
declare @tempId int
declare @idx int
declare @Ids TABLE ( ID int )

set @tempLocalIds = @in_LocalIds

while( len(@tempLocalIds) > 0)
begin
    -- find index of first ',' char
    set @idx = charindex(',', @tempLocalIds)
    -- get substring 0 to previously found index
    set @tempStrId = substring(@tempLocalIds, 0, @idx-1)
    -- convert the value
    set @tempId = convert(@tempStrId as int)
    -- remove the first number from string
    set @tempLocalIds = substring(@tempLocalIds, @idx, len(@tempLocalIds) - @idx -1) 


    -- insert into the temp table
    insert into @Ids(ID)
    values (@tempId)

end


SELECT * FROM TABLE1 WHERE LocalId in (select ID from @Ids) AND UserId = @in_UserId
END
go

【讨论】:

  • 能否提供示例代码。
  • 我在运行存储过程时收到此错误 - 传递给 LEFT 或 SUBSTRING 函数的长度参数无效。 while 循环永远不会结束。
  • 在最后一个子字符串之前添加几个打印:print @tempLocalIdsprint @idxprint len(@tempLocalIds),以检查系统是否未尝试获取长度大于总字符串长度的子字符串。
猜你喜欢
  • 2020-04-17
  • 2011-08-29
  • 2015-06-20
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多