我正在尝试通过 SQL 命令提取最后一个插入自动生成的 RowID(或键)并将其存储为 C# 变量。
我可以做第一部分,但没有做第二部分......
更新:-
Int32 newRowID = 0;
// -------------------------------------------------------------------- //
// SQL Query-1: to store validated information in the Enrollment table. //
// -------------------------------------------------------------------- //
SqlConnection Connection = new SqlConnection(xxx_DBConnect.SqlServerConnection);
String strSQL = " OPEN SYMMETRIC KEY zzzzzzzKey DECRYPTION BY CERTIFICATE zzzzzzzCertificate1"
+ " INSERT INTO [xxx].[dbo].[yyy]"
+ " (Type, Name, DBA, Address1, City, State, Zip, TIN, TINLast4, NPI)"
+ " values (@Type, @Name, @DBA, @Address1, @rCity, @State, @Zip, ENCRYPTBYKEY(KEY_GUID('zzzzzzz'),CONVERT(VARCHAR, @TIN)), @TINLast4, @rNPI)"
+ " CLOSE SYMMETRIC KEY zzzzzzzKey;"
+ " SET @RowId = SCOPE_IDENTITY();";
// Connection is explicitly opened.
Connection.Open();
SqlCommand command = new SqlCommand(strSQL, Connection);
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@RowId";
parameter.SqlDbType = SqlDbType.Int;
parameter.Direction = ParameterDirection.Output;
command.Parameters.Add(parameter);
command.Parameters.AddWithValue("@Type", _type);
command.Parameters.AddWithValue("@Name", _Name);
command.Parameters.AddWithValue("@DBA", _DBA);
command.Parameters.AddWithValue("@Address1", _address);
command.Parameters.AddWithValue("@City", _city);
command.Parameters.AddWithValue("@State", _state);
command.Parameters.AddWithValue("@Zip", _zip);
command.Parameters.AddWithValue("@TIN", _tIN);
command.Parameters.AddWithValue("@TINLast4", _TINlast4);
command.Parameters.AddWithValue("@NPI", _nPI);
//newRowID = (Int32)command.ExecuteScalar();// <--- how do I write this in the correct syntax ?? ....
command.ExecuteNonQuery();
if (parameter.Value != DBNull.Value)
{
newRowID = (int)parameter.Value;
}
Connection.Close();
我没有收到错误,但是 newRowID = 0...预期结果是 130...。我假设返回的 SQLparamater 返回一个“0”
是否有编写以下语法的正确方法?
这样我就可以在我的 C# 代码中的任何地方访问变量 newRowID 并使用它......