C# 带有ExecuteOnQuery和ExecuteScalar的存储过程插入
SQL插入问题。运行存储过程将行插入表并返回创建的ID。当我像这样运行它,并且有一个输出参数@ID并使用ExecuteNonQuery()时,它会为我的int ID返回-1,但会返回插入的ID。既然插入了记录,它不应该返回1吗。我想使用ExecuteOnQuery检查插入的记录,然后获取插入的ID SQL插入C# 带有ExecuteOnQuery和ExecuteScalar的存储过程插入,c#,sql,insert,executenonquery,executescalar,C#,Sql,Insert,Executenonquery,Executescalar,SQL插入问题。运行存储过程将行插入表并返回创建的ID。当我像这样运行它,并且有一个输出参数@ID并使用ExecuteNonQuery()时,它会为我的int ID返回-1,但会返回插入的ID。既然插入了记录,它不应该返回1吗。我想使用ExecuteOnQuery检查插入的记录,然后获取插入的ID SQL插入 @person bigint, @date datetime, @ID bigint OUTPUT AS BEGIN SET NOCOUNT ON; INSERT IN
@person bigint,
@date datetime,
@ID bigint OUTPUT
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO table(person,DATE_ADDED)
VALUES (@person,@date)
SELECT @ID = SCOPE_IDENTITY()
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@person", person);
cmd.Parameters.AddWithValue("@date", DateTime.Now);
SqlParameter output = new SqlParameter("@ID", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
int idinserted = (int)cmd.ExecuteNonQuery();
if (idinserted > 0)
{
int ID = output.Value;
}
当我使用ExecuteScalar()执行插入和c#操作时
ExecuteScalar()
抛出以下错误
“指定的强制转换无效
除去
因为这会删除行数!很抱歉,这不是刚刚检查的问题。好的,但记录是否已插入?啊……这就是问题所在。我花了太多时间研究拼写和连接问题。
SQL INSERT
@person bigint,
@date datetime
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO table(person ,DATE_ADDED)
VALUES(@person,@date )
SELECT SCOPE_IDENTITY()
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@person", person);
cmd.Parameters.AddWithValue("@date", DateTime.Now);
long ID = (long)cmd.ExecuteNonScalar();
SET NOCOUNT ON;