如何将内联SQL转换为SQL Server中的存储过程

时间:2014-11-11 05:15:15

标签: c# asp.net sql-server sql-server-2008

下面显示的代码是作为内联SQL语句创建的。如何将此代码写为存储过程?

代码是:

public Stream SelectEmployeeImageByID(int theID)
{
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString());
        string sql = "SELECT Image FROM Employees WHERE EmployeeId = @EmployeeId";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@EmployeeId", theID);

        connection.Open();
        object theImg = cmd.ExecuteScalar();

        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

2 个答案:

答案 0 :(得分:1)

你可以这样做

create procedure SelectEmployeeImage(@employee int)
as
begin
   SELECT Image FROM Employees WHERE EmployeeId = @EmployeeId 
end

那么你的代码就是这个表格

public Stream SelectEmployeeImageByID(int theID)
    {
        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString());
        string sql = "SelectEmployeeImage";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@EmployeeId", theID);
        connection.Open();
        object theImg = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

希望这会对你有所帮助

答案 1 :(得分:0)

创建存储过程

Create procedure SP_InsertEmployee
as
@EmployeeId int 
BEGIN

SELECT Image FROM Employees WHERE EmployeeId=@EmployeeId

END

你应该设置CommandType=StoredProcedure,其余的将是相同的

cmd.CommandType = CommandType.StoredProcedure;

建议

始终使用自动处理连接的using

using (SqlConnection con = new SqlConnection())
{
con.open();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{

//object theImg = cmd.ExecuteScalar();

}

con.Dispose();
}