0
Dim MaxItemID As Integer
Dim objCMD As New SqlCommand(StrSql, objConn)  
MaxItemID = IIf(IsDBNull(objCMD.ExecuteScalar()), 0, objCMD.ExecuteScalar()) + 1

我如何在 C# 中做到这一点?

4

3 回答 3

1
int MaxItemID = 0;
using(SqlCommand objCMD = new SqlCommand(StrSql, objConn))
{
    MaxItemID = (Converter.IsDBNull(objCMD.ExecuteScalar()) ? 0 : objCMD.ExecuteScalar()) + 1;
}
于 2012-09-29T09:32:54.853 回答
0
int MaxItemID;
SqlCommand objCMD =new SqlCommand (StrSql, objConn);
MaxItemID = IsDBNull(objCMD.ExecuteScalar()? 0: objCMD.ExecuteScalar()) + 1;
于 2012-09-29T09:33:44.860 回答
0

这应该这样做(并避免执行 SQL 两次):

var objCMD = new SqlCommand(StrSql, objConn);
var sqlRes = objCMD.ExecuteScalar();
int maxItemID = 1 + (Convert.IsDBNull(sqlRes) ? 0 : (int)sqlRes);

注意 VB 会将object返回值隐式转换ExecuteScalar为 an int,但 C# 不会。

于 2012-09-29T09:36:07.277 回答