存储过程检查/比较列的值

时间:2018-03-09 01:25:01

标签: c# sql-server stored-procedures

VS代码

try
{
    DBContext cl = new DBContext();
    SqlConnection cn = new SqlConnection(DBContext.ConnectionString);
    SqlCommand cmd = new SqlCommand("UERMEMR..ys_Update_Borrow", cn);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("BORROWING_ID", txtbox_borrow_ID.Text);

    cn.Open();
    cmd.ExecuteNonQuery();
    cn.Close();
    MessageBox.Show("Closed Successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

    txtbox_borrow_ID.Clear();
    {
        DLPatients p1 = new DLPatients();
        dt = p1.GetRecord();
        this.Grid_borrow2.SetDataBinding(dt, "", true);
    }
}
catch (Exception userEx)
{
    MessageBox.Show("Error : " + userEx.Message);
}

SP代码(我会更改)

CREATE PROCEDURE [dbo].[ys_Update_Borrow]
(@BORROWING_ID int,
@STATUS varchar (50) = 'Closed',
@DATE_CLOSED datetime = null)

AS
UPDATE MEDREC_BORROWING
SET STATUS = @STATUS,
    DATE_CLOSED = COALESCE(@DATE_CLOSED , GETDATE())
FROM MEDREC_BORROWING
WHERE BORROWING_ID = @BORROWING_ID
GO

我想首先检查状态是否已关闭并向VS输出消息或错误。如果没有关闭,请继续我的SP。

请帮忙。

1 个答案:

答案 0 :(得分:0)

  

我想首先检查状态是否已关闭

好的,所以你想检查Status = 'Closed'是否只是通知用户(或显示错误),但是如果它没有关闭,你想要使用你的存储过程关闭它。您的存储过程代码已经存在。

以下是如何检查:

var command = new System.Data.SqlClient.SqlCommand();
command.CommandType = CommandType.Text;
command.Parameters.Add("BORROWING_ID", SqlDbType.VarChar).Value = txtbox_borrow_ID.Text;
command.CommandText = "SELECT STATUS FROM MEDREC_BORROWING WHERE BORROWING_ID = @BORROWING_ID ";
string status  = command.ExecuteScalar().ToString();
if (status == "Closed")
{
    MessageBox.Show("Already closed!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
    // put your stored procedure code here and call it
}