Reputation: 3
In ASP.NET, can a 'select-query' be dynamic as follows ? This throws an error, how can this be achieved?
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>
Upvotes: 0
Views: 110
Reputation: 1725
Use a command object and replace the placeholder text with the column names.
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 Ref: http://msdn.microsoft.com/en-us/library/fksx3b4f.aspx
Upvotes: 0
Reputation: 152576
You can't so that in SQL, let alone ASP.NET. You'll have to generate the SQL by inserting the column name into the string.
I don't know of a way to do that declaratively - you're probably going to have to do the binding in code-behind and build the SQL dynaimcally:
string SQL = "SELECT TOP 30 [date], [" + tc + "] FROM [tbl_TC] WHERE ([ID] = ?) ORDER BY [date]";
Upvotes: 1