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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21655110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:00:46  来源:igfitidea点击:

Conversion failed when converting the nvarchar value ... to data type int

sql

提问by user3288804

I created the procedure listed below:

我创建了下面列出的程序:

CREATE procedure getdata
(
    @ID int,
    @frm varchar(250),
    @to varchar(250)
)
AS
BEGIN

DECLARE @SQL nvarchar(500)


set @SQL = 'select'
set @SQL = @SQL + ' EmpName, Address, Salary from Emp_Tb where 1=1 '

IF (@ID <> '' and @ID is not null)     
  Begin     
   SET @sql=@sql+' AND Emp_Id_Pk=' +@ID   
  End 
END

print @sql
--execute (@sql)

I try to execute it using:

我尝试使用以下方法执行它:

**execute getdata 3,'','';**

But I'm getting the following error:

但我收到以下错误:

Conversion failed when converting the nvarchar value 'select EmpName, Address, Salary from Emp_Tb where 1=1 AND Emp_Id_Pk=' to data type int

将 nvarchar 值 'select EmpName, Address, Salary from Emp_Tb where 1=1 AND Emp_Id_Pk=' 转换为数据类型 int 时转换失败

Please help.

请帮忙。

回答by Avi Turner

You are trying to concatenate a string and an integer.
You need to cast@IDas a string.
try:

您正在尝试连接一个字符串和一个整数。
你需要@ID作为一个字符串。
尝试:

SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))

回答by csk

Try Using

尝试使用

CONVERT(nvarchar(10),@ID)

This is similar to cast but is less expensive(in terms of time consumed)

这类似于 cast 但更便宜(就消耗的时间而言)

回答by Seyed Hussein Mirzaki

I was using a KEY word for one of my columns and I solved it with brackets []

我在我的一个专栏中使用了一个关键词,我用 brackets []

回答by Ibrahim Béji

I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.

我遇到了同样的问题,我删除了相关列的约束,它对我有用。您可以检查文件夹约束。

Capture: http://i.stack.imgur.com/9Wccz.png

捕获:http: //i.stack.imgur.com/9Wccz.png

回答by Basheer AL-MOMANI

You got this Error because you tried to convert column DataTypefrom Stringto intwhich is

你得到了这个错误,因为你试图列转换DataTypeStringint这是

leagal if and only if

leagal if and only if

you dont have row in that table with string content inside that column

您在该表中没有该列中包含字符串内容的行

so just make sure your previously inserted Rowsis compatible with the new changes

所以只要确保你之前插入的 Rowscompatible with the new changes