[英]C# sqlserver stored procedure parameters
I have a stored procedure that has an update statement. 我有一个具有更新语句的存储过程。 It takes 3 parameters: ID,Status,Date
它包含3个参数:ID,Status,Date
I have written a C# program to call this procedure. 我已经编写了一个C#程序来调用此过程。 If the status is -1, I want the date to be null in the table and if status is 1, date should be current date.
如果状态为-1,则我希望表中的日期为空,如果状态为1,则日期应为当前日期。
Int32 rowsAffected = 0;
string datenow =null;
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(
"usp_UpdateProc", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@status", SqlDbType.Int);
cmd.Parameters["@status"].Value = status;
if(status != 1)
datenow = DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt");
cmd.Parameters.AddWithValue("@datenow", @datenow);
cmd.Parameters.Add(
new SqlParameter("@ID", @ID));
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{ //throw ep
}
When I do this status and date fields are both nulls in Database. 执行此操作时,状态和日期字段在数据库中均为空。 I am not sure why this is happening?
我不确定为什么会这样? Thanks Rashmi
谢谢拉什米
I would try to assign the values like this instead and see if it makes a difference: 我会尝试分配这样的值,看看是否有区别:
SqlParameter stat = cmd.Parameters.AddWithValue("@status" ,status);
stat.dbType = SqlDbType.Int;
DateTime? dt = (status == -1)? null : DateTime.Now;
SqlParameter dateParam = cmd.Parameters.AddWithValues("@datenow", dt ?? DBNull.Value);
dateParam.dbType = SqlDbType.DateTime;
I see some issues in your code: 我在您的代码中看到了一些问题:
Please do not put empty try/catches and display the exception instead so you can better see what is going wrong. 请不要放空try / catches并显示异常,这样您可以更好地了解出了什么问题。
I suggest this: 我建议这样:
SqlCommand cmd = new SqlCommand("usp_UpdateProc", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@status", status);
if(status == -1)
cmd.Parameters.AddWithValue("@datenow", DBNull.Value);
else
cmd.Parameters.AddWithValue("@datenow", DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"));
cmd.Parameters.AddWithValue("@ID", @ID);
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{
MessageBox.Show(ep.ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.