Çıkış parametre değeri elde ADO.NET içinde
Benim saklı yordam çıkış parametresi vardır:
@ID INT OUT
Nasıl bu kullanarak ADO.NET alabilir miyim?
using (SqlConnection conn = new SqlConnection(...))
{
SqlCommand cmd = new SqlCommand("sproc", conn);
cmd.CommandType = CommandType.StoredProcedure;
// add parameters
conn.Open();
// *** read output parameter here, how?
conn.Close();
}
CEVAP
Diğer tepki gösterir, ama aslında senin ihtiyacın oluşturmak için SqlParameter
set Direction
Output
ve ekliyorum SqlCommand
Parameters
koleksiyon. Saklı yordamı yürütmek ve parametrenin değeri olsun.
Kod örneği kullanarak:
// SqlConnection and SqlCommand are IDisposable, so stack a couple using()'s
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("sproc", conn))
{
// Create parameter with Direction as Output (and correct name and type)
SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
// Some various ways to grab the output depending on how you would like to
// handle a null value returned from the query (shown in comment for each).
// Note: You can use either the SqlParameter variable declared
// above or access it through the Parameters collection by name:
// outputIdParam.Value == cmd.Parameters["@ID"].Value
// Throws FormatException
int idFromString = int.Parse(outputIdParam.Value.ToString());
// Throws InvalidCastException
int idFromCast = (int)outputIdParam.Value;
// idAsNullableInt remains null
int? idAsNullableInt = outputIdParam.Value as int?;
// idOrDefaultValue is 0 (or any other value specified to the ?? operator)
int idOrDefaultValue = outputIdParam.Value as int? ?? default(int);
conn.Close();
}
Tür olarak ilan ver object
döküm olması gerektiği için Parameters[].Value
, alırken dikkatli olun. SqlDbType
SqlParameter
oluştururken kullanılan veritabanı türüne uygun olması gerekir. Eğer sadece konsola çıktı yapacaksan, sadece Parameters["@Param"].Value.ToString()
(Console.Write()
String.Format()
telefon üzerinden explictly veya dolaylı olarak) kullanıyor olabilirsiniz.
EDİT: 3.5 yıl ve neredeyse 20k manzarası bile hiç kimse neden benim belirtilen derleme olmadığını söyleme zahmetinde bulunmadı vardı "dikkatli ol" özgün yazı yorum. Güzel. @Stephen Kennedy ve söz konusu güncelleştirme kodunu düzenlemek maçı için @iyi yorumlardan Walter Stabosz gelen abatishchev dayalı sabit.
JavaScript bir işlev için varsayılan p...
Numaralama int değeri elde...
Nasıl URL parametre değeri olsun?...
Java içinde Geçerli Çalışma Dizini eld...
' '' deyim SEÇİN - çıkı...