简体   繁体   English

动态建立SqlDataSource的选择查询

[英]dynamically build select query for SqlDataSource

I have a drop down list populated with some table names. 我有一个下拉列表,其中填充了一些表名。 When the selection changes, GridView should reflect the changes accordingly as well. 当选择更改时,GridView也应相应地反映更改。

I can think of 1 approach that probably can work - using a Stored Procedure with parameter supplied as table name. 我可以想到一种可能可行的方法-使用带有作为表名提供的参数的存储过程。

But I am also wondering if there'd be any other ways to achieve this, well, without writing too much code preferably. 但是我也想知道是否还有其他方法可以做到这一点,而不必编写太多代码。 Any ideas? 有任何想法吗? Thanks 谢谢

As a alternative approach, you can set select command of Sqldatasource dynamically. 作为一种替代方法,可以动态设置Sqldatasource的select命令。 You need to set SelectCommandType="Text" and use code as below: 您需要设置SelectCommandType =“ Text”并使用以下代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch (DropDownList1.SelectedValue.ToString())
    {
        case "TABLE1":
            SqlDataSource1.SelectCommand = "Select fieldName from TABLE1";
            break;
        case "TABLE2":
            SqlDataSource1.SelectCommand = "Select fieldName from TABLE2";
            break;
        default:           
            SqlDataSource1.SelectCommand = "Select fieldName from TABLE";
            break;
    }
}

I would tend to agree that the stored procedure approach is preferable to the constructed SQL in both of the examples above. 我倾向于同意在上述两个示例中,存储过程方法都比构造的SQL更可取。

While not horrible in this case, you're sending a full query across the wire, which is not preferable. 虽然在这种情况下并不可怕,但是您正在通过网络发送完整的查询,这不是可取的。 Further, you can also secure direct access to the tables themselves but grant access to the SPROC so you could provide this listing capability to certain user groups without allowing them direct access. 此外,您还可以保护对表本身的直接访问,但可以授予对SPROC的访问权限,因此您可以向某些用户组提供此列出功能,而又不允许他们直接访问。

I'd recommend using the CASE statement in your stored procedure rather than constructing SQL. 我建议在您的存储过程中使用CASE语句,而不要构造SQL。 This will guarantee that you're only supporting the tables you are aware of and prohibits any abuse of the system. 这将确保您仅支持您知道的表并禁止滥用系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM