在ASP.Net gridview中显示存储过程结果

时间:2012-05-21 18:49:55

标签: asp.net sql-server stored-procedures gridview

我在网格视图中显示一些SQL Server存储过程结果时已经苦苦挣扎了一段时间。我收到以下错误:

  

在该网站上找不到名为“Hora”的字段或属性   选定的数据源

我已经彻底检查过任何拼写错误或拼写错误。但有一件事:存储过程显示一个表,其中source是另一个临时表。我认为这个问题与此有关。

这是我的gridview aspx代码:

<asp:GridView ID="gvPosicion" runat="server" AutoGenerateColumns="False" 
        Width="915px" CellPadding="4" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <asp:BoundField DataField="Hora" HeaderText="Hora" SortExpression="Hora" 
                ReadOnly="True" />
            <asp:BoundField DataField="Direccion" HeaderText="Direccion" 
                SortExpression="Direccion" />
            <asp:BoundField DataField="Posicion" HeaderText="Posicion" 
                SortExpression="Posicion" />
        </Columns>
        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>

这是我在点击事件中的代码隐藏:

System.Data.DataTable dt = reporte.GetData(int.Parse(ddlChofer.SelectedValue), int.Parse(ddlVehiculo.SelectedValue), Convert.ToDateTime(txtFecha.Text));

if (dt.Rows.Count > 0)
{
   foreach (DataRow dr in dt.Rows)
   {
       string salida = dr["Salida"].ToString();
       string llegada = dr["Llegada"].ToString();

       if (salida != "" && llegada != "")
       {
          DataSetTableAdapters.sp_ChecarVehiculosTableAdapter cv = new DataSetTableAdapters.sp_ChecarVehiculosTableAdapter();
          gvPosicion.DataSource = cv.GetData(int.Parse(ddlVehiculo.SelectedValue), DateTime.Parse(salida), DateTime.Parse(llegada)).ToString();
          gvPosicion.DataBind();

这是我的存储过程,我认为这是一个混乱的LOL,但实际上我只是一个SQL初学者。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[sp_ChecarVehiculos]
@carro int,
@f1 datetime,
@f2 datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT cve_punto_gps,fecha_servidor, latitud, longitud, velocidad,direccion
INTO #temp
FROM [desarrollo].[dbo].[vehiculo_punto_gps]
WHERE cve_vehiculo=@carro
and fecha_servidor>=@f1
and fecha_servidor<=@f2
DECLARE @cve_inicio as int,
    @cve_final as int,
    @fecha_inicio as datetime,
    @fecha_final as datetime,
    @latitud_inicio as decimal(18,15),
    @latitud_final as decimal (18,15),
    @longitud_inicio as decimal (18,15),
    @longitud_final as decimal (18,15),
    @velocidad_inicio as int,
    @velocidad_final as int,
    @direccion_inicio as nvarchar(150),
    @direccion_final as nvarchar(150)
DECLARE VehicleCursor CURSOR FAST_FORWARD FOR 
SELECT  cve_punto_gps, 
    fecha_servidor,
    latitud,
    longitud,
    velocidad,
    direccion
FROM #temp
ORDER BY cve_punto_gps
 OPEN VehicleCursor FETCH NEXT FROM VehicleCursor INTO @cve_inicio, @fecha_inicio,        @latitud_inicio, @longitud_inicio, @velocidad_inicio, @direccion_inicio
FETCH NEXT FROM VehicleCursor INTO @cve_final, @fecha_final, @latitud_final, @longitud_final,@velocidad_final, @direccion_final
create table #tempb(cve int, fecha datetime, posicion nvarchar(60), velocidad int, direccion nvarchar(150) )
WHILE @@FETCH_STATUS = 0 BEGIN
    IF (round(@latitud_inicio,4,1) != round(@latitud_final,4,1))
    BEGIN   
        IF DATEDIFF(MI,@fecha_inicio,@fecha_final) >=3
        BEGIN           
            IF @velocidad_inicio !=0
            BEGIN
                declare @posicion nvarchar(60)=(cast(@latitud_inicio as nvarchar(30)) +' '+ cast(@longitud_inicio as nvarchar(30)))

                insert #tempb values(@cve_inicio,@fecha_inicio, @posicion,@velocidad_inicio, @direccion_inicio)
                --PRINT 'Posición: '+cast(@fecha_inicio as nvarchar(30))+' en '+@direccion_inicio+'('+@posicion+')';
            END     
        END
    END
    SET @cve_inicio = @cve_final
    SET @fecha_inicio = @fecha_final
    SET @latitud_inicio=@latitud_final
    SET @longitud_inicio=@longitud_final
    SET @velocidad_inicio=@velocidad_final
    SET @direccion_inicio=@direccion_final
    FETCH NEXT FROM VehicleCursor INTO @cve_final, @fecha_final, @latitud_final, @longitud_final, @velocidad_final, @direccion_final
END   
CLOSE VehicleCursor 
DEALLOCATE VehicleCursor
select convert(varchar(8),fecha,108) as 'Hora', direccion as 'Direccion', posicion as   'Posicion'  /*into #tempc */from #tempb
/*select * from #tempc*/
END

如果您想知道我为什么要创建该存储过程,请检查以下post。另外,如果我在SQL中使用某些参数执行存储过程,则不会出现错误。

提前致谢。

1 个答案:

答案 0 :(得分:1)

除了我在评论中提供的建议之外,我认为这将给出您在过程中没有所有变量,游标和临时表的结果。请尝试一下,如果我错误地解释了你的任何逻辑,请告诉我。

ALTER PROCEDURE [dbo].[sp_ChecarVehiculos]
  @carro int,
  @f1 datetime,
  @f2 datetime
AS
BEGIN
  SET NOCOUNT ON;

  ;WITH d AS
  (
    SELECT 
        cve_punto_gps, fecha_servidor, velocidad, direccion, latitud, longitud
        posicion = RTRIM(latitud) + ' ' + RTRIM(longitud),
        rn = ROW_NUMBER() OVER (ORDER BY fecha_servidor)
        FROM [desarrollo].[dbo].[vehiculo_punto_gps]
        WHERE carro = @carro
        AND fecha_servidor >= @f1
        AND fecha_servidor <= @f2
  )
  SELECT 
    Hora = CONVERT(CHAR(8), d.fecha_servidor, 108),
    d.direccion, d.posicion
  FROM d LEFT OUTER JOIN d AS d2
  ON d.rn = d2.rn - 1
  WHERE d.rn = 1
  OR 
  (
    DATEDIFF(MINUTE, d.fecha_servidor, COALESCE(d2.fecha_servidor, GETDATE())) >= 3 
    AND ROUND(d.latitud, 4, 1) <> ROUND(d2.latitud, 4, 1)
    AND d.velocidad <> 0
  )
  ORDER BY d.fecha_servidor;
END
GO

如果不正确,则不应进行太多编辑以纠正我根据您现有代码所犯的错误。这不仅在SQL Server中更有效,而且还应该使您的C#代码更容易处理输出。

编辑示例显示所选行之间的时间延迟:

ALTER PROCEDURE [dbo].[sp_ChecarVehiculos]
  @carro int,
  @f1 datetime,
  @f2 datetime
AS
BEGIN
  SET NOCOUNT ON;

  ;WITH d AS
  (
    SELECT 
        cve_punto_gps, fecha_servidor, velocidad, direccion, latitud, longitud
        posicion = RTRIM(latitud) + ' ' + RTRIM(longitud),
        rn = ROW_NUMBER() OVER (ORDER BY fecha_servidor)
        FROM [desarrollo].[dbo].[vehiculo_punto_gps]
        WHERE cve_vehiculo = @carro
        AND fecha_servidor >= @f1
        AND fecha_servidor <= @f2
  ), s AS
  (
    SELECT 
      Hora = CONVERT(CHAR(8), d.fecha_servidor, 108),
      d.direccion, d.posicion, d.fecha_servidor,
      rn = ROW_NUMBER() OVER (ORDER BY d.fecha_servidor)
    FROM d LEFT OUTER JOIN d AS d2
    ON d.rn = d2.rn - 1
    WHERE d.rn = 1
    OR 
    (
      DATEDIFF(MINUTE, d.fecha_servidor, 
        COALESCE(d2.fecha_servidor, GETDATE())) >= 3 
      AND ROUND(d.latitud, 4, 1) <> ROUND(d2.latitud, 4, 1)
      AND d.velocidad <> 0
    )
  )
  SELECT s.Hora, delta = DATEDIFF(MINUTE, s.fecha_servidor, s2.fecha_servidor),
    s.direccion, s.posicion
  FROM s LEFT OUTER JOIN s as s2 ON s.rn = s2.rn - 1
  ORDER BY s.rn;
END
GO