繁体   English   中英

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

[英]Conversion failed when converting the nvarchar value 'OrgID' to data type int

因此,我正在自学如何在SQL Server Management Studio中执行存储过程,并且试图替换Visual Studio中C#代码中的字符串查询。 我原来的代码是

 InsertQuery = "INSERT INTO License (OrgID, LicensingKey) VALUES (@OrgID, @LicensingKey)"; // Query to insert into the database table.
 SqlCommand cmd = new SqlCommand(InsertQuery, con);
 cmd.Parameters.Add("@LicensingKey", SqlDbType.Int).Value = LicensingKey;  
 cmd.Parameters.Add("@OrgID", SqlDbType.Int).Value = OrgID;
 cmd.ExecuteNonQuery();

其中,OrgID和LicensingKey是此代码所在的方法传递的两个整数。

我在数据库中创建的存储过程是这样的:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[LicenseInsert]
@OrgID int = OrgID,
@LicensingKey int = LicensingKey

AS
BEGIN
SET NOCOUNT ON;
INSERT INTO License (OrgID, LicensingKey) 
VALUES (@OrgID, @LicensingKey)
END

现在我用的相同的代码替换为:

InsertQuery = "EXEC LicenseInsert "; // Query to insert into the database table.
SqlCommand cmd = new SqlCommand(InsertQuery, con);
cmd.ExecuteNonQuery();

但是这给了我“将nvarchar值'OrgID'转换为数据类型int时转换失败”的错误,这是说

cmd.ExecuteNonQuery(); 

是罪魁祸首。

有人可以引导我了解我做错了什么吗? 非常感谢你!

我希望您会收到某种缺少参数的错误,但是要执行存储过程,您只需要使用存储过程名称并将命令类型更改为StoredProcedure

InsertQuery = "LicenseInsert"; // Query to insert into the database table.
SqlCommand cmd = new SqlCommand(InsertQuery, con);
cmd.CommandType = CommandType.StoredProcedure;  // <------------

cmd.Parameters.Add("@LicensingKey", SqlDbType.Int).Value = LicensingKey;  
cmd.Parameters.Add("@OrgID", SqlDbType.Int).Value = OrgID;

cmd.ExecuteNonQuery();

另外,我认为您的存储过程定义无效。 它应该是:

ALTER PROCEDURE [dbo].[LicenseInsert]
@OrgID int,
@LicensingKey int

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM