【问题标题】:How to convert Inline SQL to a stored procedure in SQL Server如何将内联 SQL 转换为 SQL Server 中的存储过程
【发布时间】:2014-11-11 05:15:14
【问题描述】:

下面显示的我的代码是作为内联 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();
        }
    }

【问题讨论】:

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


【解决方案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();
        }
    }

希望对你有帮助

【讨论】:

    【解决方案2】:

    创建存储过程

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 2013-10-10
      • 2020-10-12
      • 2020-06-06
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2014-11-01
      相关资源
      最近更新 更多