SqlDataSource中的子查询导致错误(asp.net)

本文关键字:错误 asp net 查询 SqlDataSource | 更新日期: 2023-09-27 18:05:45

错误:(Microsoft Visual Studio使用ASP.NET/C#):

子查询返回多个值。这是不允许的子查询在=,!=,<, <=,>,>=或子查询用作一个表达式。

详细信息:前面的错误是由以下代码引起的。它是一个GridView和关联的SQLDataSource。

<asp:GridView ID="gGrid" runat="server" AutoGenerateColumns="False" 
    DataSourceID="sqlAll" AllowPaging="True" 
    onpageindexchanging="grdGrid_PageIndexChanging">
    <Columns>
        <asp:BoundField DataField="A" HeaderText="A" 
            SortExpression="A" />
        <asp:BoundField DataField="G" HeaderText="G" 
            SortExpression="PeriodCode" />
        <asp:BoundField DataField="Value" HeaderText="Value" SortExpression="Value" />
    </Columns>
</asp:GridView>

    <asp:SqlDataSource ID="sqlAll" runat="server" 
        ConnectionString="<%$ ConnectionStrings:ConnectionDB01 %>" 
        SelectCommand="SELECT [A], [G], [H] FROM [Table1] 
    WHERE [B] = 
        (SELECT [B] 
          FROM [Table2] 
            WHERE [C] = @C) 
    AND ([D] = 
        (SELECT [D] 
            FROM [Table3] 
              WHERE [E] = @E))
    AND ([A] < @A) AND ([A] > @A2)">
        <SelectParameters>
            <asp:ControlParameter ControlID="ddlBlah2" Name="AreaName" 
                PropertyName="SelectedValue" Type="String" />
            <asp:ControlParameter ControlID="ddlBlah" Name="B" 
                PropertyName="SelectedValue" Type="String" />
            <asp:ControlParameter ControlID="txtEndA" Name="A" 
                PropertyName="Text" Type="Decimal" />
            <asp:ControlParameter ControlID="txtStartA" Name="A2" 
                PropertyName="Text" Type="Decimal" />
         </SelectParameters>
    </asp:SqlDataSource>
    <br />

(@Letter表示它们来自下拉列表引用)

注释:很明显,代码中有子查询。但是,如何绕过非子查询限制呢?这些事情通常是如何处理的?

SqlDataSource中的子查询导致错误(asp.net)

 (SELECT [B] 
      FROM [Table2] 
        WHERE [C] = @C) 
 change this query to like this
     (SELECT TOP 1[B] 
       FROM [Table2] 
        WHERE [C] = @C) 

 or use IN instead of =
     WHERE [B] IN 
      (SELECT [B] 
      FROM [Table2] 
        WHERE [C] = @C) 

子查询的问题是,当您尝试执行诸如=,<, <=,>,>=之类的操作时,它只能将一个值与另一个值进行比较,而不能将一个值与一组值进行比较。假设你的子查询SELECT [B] FROM [Table2] WHERE [C] = @C返回多个值,它将抛出这个错误

你可以使用这个子查询,如果你确定子查询将只返回一个值(可能是因为[C]是主键),否则你可以使用@Devesh答案