SQL Server存储过程出错&;C#
本文关键字:amp 出错 Server 存储过程 SQL | 更新日期: 2023-09-27 18:00:08
我一直在开发一个存储过程,以便从表中获取寄存器,因此我构建了以下查询来实现这一点:
ALTER procedure [dbo].[procedure_odd]
@codSeccion int,
@NomDoce varchar(500),
@codMate varchar(500)
as
begin
declare @hora varchar(50);
set @hora = (
select b.man_nomhor
from ra_hpl_horarios_planificacion a
inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo
where a.hpl_codcil = 100
and a.hpl_codemp = (select emp_codigo from pla_emp_empleado
where emp_nombres_apellidos = @NomDoce)
and a.hpl_codmat = @codMate
and a.hpl_descripcion = @codSeccion)
return @hora
end
我在SQL Server控制台中测试了这个查询(只是查询,而不是带有查询的存储过程),它运行得很好。问题是,当我从C#调用它时,无论我尝试什么,它都不起作用!此外,我还尝试开发一个带有输出参数的存储过程,但没有结果。
此外,我还尝试过其他方式(效果非常好!):
select b.man_nomhor
from ra_hpl_horarios_planificacion a
inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo
where a.hpl_codcil = 100
and a.hpl_codemp =
(select emp_codigo from pla_emp_empleado
where emp_nombres_apellidos = 'julio escobar')
and a.hpl_codmat = 'FONO-I'
and a.hpl_descripcion = 1;
这是我在C#(我的11000解决方案)上的代码:
public String horarios(int Seccion, string NomDocent, string CodMate)
{
cn.Open();
cmd.Connection = cn;
cmd.CommandText = "select b.man_nomhor from ra_hpl_horarios_planificacion
a inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo where
a.hpl_codcil = 100 and a.hpl_codemp =(select emp_codigo from
pla_emp_empleado where emp_nombres_apellidos = '" + NomDocent +
"') and a.hpl_codmat = '" + CodMate + "' and a.hpl_descripcion = '" + Seccion + "'";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (dr.Read())
{
msj = dr[0].ToString();
}
}
cn.Close();
return msj;
}
当我运行Visual Studio时,它根本不会显示任何错误,但在变量MSJ中,它设置了一个空字符串,如下所示MSJ=";
这一定很容易,但只是(相信)我已经尽了很大努力才找到bno结果的解决方案,请帮忙!
看起来Seccion
(因此a.hpl_descripcion
)是整数,但您的查询像文字一样在其周围放置撇号。
尝试删除撇号:
... + "' and a.hpl_descripcion = " + Seccion;
如果这确实是问题所在,那么参数化查询可以消除以下类型的错误:
cmd.CommandText = "... and a.hpl_codemp =(select emp_codigo from pla_emp_empleado where emp_nombres_apellidos = @NomDocent) and a.hpl_codmat = @CodMate and a.hpl_descripcion = @Seccion";
cmd.AddParameterWithValue("@NomDocent", NomDocent);
cmd.AddParameterWithValue("@CodMate", CodMate);
cmd.AddParameterWithValue("@Seccion, Seccion);
dr = cmd.ExecuteReader();
很少有东西:
-
如果希望这是一个存储过程,请确保设置
command.CommandType = CommandType.StoredProcedure
。 -
您不需要调用return或设置变量来返回您所拥有的文本。相反,只需让select语句返回一个字段:
ALTER procedure [dbo].[procedure_odd] @codSeccion int, @NomDoce varchar(500), @codMate varchar(500) as begin select top 1 b.man_nomhor from ra_hpl_horarios_planificacion a inner join ra_man_grp_hor b on a.hpl_codman = b.man_codigo where a.hpl_codcil = 100 and a.hpl_codemp = (select emp_codigo from pla_emp_empleado where emp_nombres_apellidos = @NomDoce) and a.hpl_codmat = @codMate and a.hpl_descripcion = @codSeccion) END
完成后,只需使用dataReader执行存储过程,它将返回您的值。如果你需要更多信息,我可以编辑我的答案来澄清。