sql查询中的列的变量选择

时间:2014-07-02 21:26:15

标签: asp.net sql ms-access

在ASP.NET中,'select-query'可以动态如下吗? 这会引发错误,如何实现?

SelectCommand="SELECT TOP 30 [date],**[@tc]** FROM [tbl_TC] WHERE ([ID] = ?) ORDER BY [date]">
<SelectParameters>
**<asp:QueryStringParameter Name="@tc" QueryStringField="tc" />**
<asp:QueryStringParameter Name="ID" QueryStringField="pid" Type="String" />
</SelectParameters>

2 个答案:

答案 0 :(得分:1)

你不能这样在 SQL 中,更不用说ASP.NET了。您必须通过将列名插入字符串来生成SQL。

我不知道如何以声明方式执行此操作 - 您可能必须在代码隐藏中进行绑定并在动态上构建SQL:

string SQL = "SELECT TOP 30 [date], [" + tc + "] FROM [tbl_TC] WHERE ([ID] = ?) ORDER BY [date]";

答案 1 :(得分:0)

使用命令对象并将占位符文本替换为列名。

Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

Dim qryString = "SELECT TOP 30 [date],**[@tc]** FROM [tbl_TC] WHERE ([ID] = [?]) ORDER BY [date]"

qryString = qryString.Replace("**[@tc]**", "yourcolumnnameshere").replace("[?]", "datequerystringhere")

cmd.CommandText = qryString
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1

sqlConnection1.Open()

reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.

sqlConnection1.Close()

MSDN参考:http://msdn.microsoft.com/en-us/library/fksx3b4f.aspx