gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:14:51 26 4
gpt4 key购买 nike

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

最佳答案

你可以这样做

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

希望对你有帮助

关于c# - 如何将内联 SQL 转换为 SQL Server 中的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26857993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com