0

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>

2 Answers 2

1

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]";
Sign up to request clarification or add additional context in comments.

3 Comments

sounds right, but the [] around [" + tc + "] will likely make the database engine take that to mean one column, even if it's a list of columns. removing the [] from the string here and including them in the tc variable should work
@Twelfth I included the brackets because the code in the question had them, which makes me think that the intent is to only have one column.
Thank you guys. I was trying to get it done on ASP side which is not possible , so i have to dynamically select columns in the code (vb)
0

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

1 Comment

Thanks @GJKH for the complete solution, however i feel its more straightforward to append the query string with a variable as suggested by Stanley.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.