我有一个使用事务的SQL查询,并使用返回指示失败或成功,就像这样:的ExecuteScalar返回null
BEGIN
DECLARE @intErrorCode INT;
DECLARE @emailAutoIncrement INT;
BEGIN TRAN
INSERT INTO Accounts (blabla, blabla2)
VALUES (somevalue, somevalue2)
Select @intErrorCode = @@ERROR
if (@intErrorCode <> 0) GOTO PROBLEM
COMMIT TRAN
RETURN 1
PROBLEM:
if (@intErrorCode <> 0) Begin
Rollback Tran
RETURN 0
END
END
从代码,我用sqlCommand.ExecuteScalar()
认为这会给我1或0,但这总是返回false。另外,我遇到的另一个问题是,当sql中发生异常并且程序要返回0时,它实际上会返回异常。
那么RETURN 0
是无用的,因为它总是被异常覆盖?
要添加一些更多的信息,SQL查询是一个存储过程,它被称为像这样:
myCommand.CommandText = "createAccount";
myCommand.CommandType = CommandType.StoredProcedure;
//Add parameters here
using (myReader)
{
var test = myCommand.ExecuteScalar();
}
您是否尝试过在事务范围内移动变量声明? – 2012-04-26 11:48:50
为什么?这似乎没有关系。事务工作并返回从SQL Management Studio运行时的值,问题出自我的C#代码。 – TheGateKeeper 2012-04-26 11:52:49
尝试SET @intErrorCode = @@ ERROR而不是SELECT - 请参阅我的答案以获得完整解决方案 – DaveHogan 2012-04-26 11:57:05