是否可以在同一C#方法中从CommandText切换到存储过程

时间:2014-12-12 18:52:18

标签: c#

在同一方法中使用command.CommandText调用数据库后是否可以使用存储过程?例如,我想在下面的代码片段之后调用存储过程,但我不确定如何在我的代码中实现它。

示例:

var command = new SqlCommand
    {
        CommandText = "SELECT id FROM blah_tbl...",
        Connection = conn
    };

using (var reader = command.ExecuteReader())
{
        if (reader.Read())
        {
            user.Id = (int) reader["id"];
        }
}

// Stored procedure would be called next

1 个答案:

答案 0 :(得分:2)

private void ExecuteTwoCommands ()
{
    var command = new SqlCommand
    {
        CommandText = "SELECT id FROM blah_tbl...",
        Connection = conn
    };
        using (var reader = command.ExecuteReader())
    {
        if (reader.Read())
    {
        user.Id = (int) reader["id"];
    }

    // here You need to use Your stored procedure
    command.CommandText = "MyStoredProc";
    command.CommandType = CommandType.StoredProcedure;
    // do smoething with new command for exaple:
    command.ExecuteNonQuery;
}

修改

很少有人在评论中说创建新命令而不是再次使用相同的更好(确保更安全,可能性能稍差),所以你的代码看起来像这样:

private void ExecuteTwoCommands ()
{
    var command = new SqlCommand
    {
        CommandText = "SELECT id FROM blah_tbl...",
        Connection = conn
    };
        using (var reader = command.ExecuteReader())
    {
        if (reader.Read())
    {
        user.Id = (int) reader["id"];
    }

    SqlCommand newCommand = new SqlCommand();
    newCommand.CommandText = "MyStoredProc";
    newCommand.CommandType = CommandType.StoredProcedure;
    // do smoething with new command for exaple:
    newCommand.ExecuteNonQuery;
}