0

Apologizes if this has been asked before but I was not sure even how to search for this.

I am using VB for code behind & want I am trying to find out is this;

I have a defined SqlCommand:

Dim cmd As New SqlCommand("Select [Field1], [Field2], [Field3] From [Table] Where [FieldX] = @parameter ")

How can I add another field using code with out changing the base SqlCommand?

So the temp SqlCommand would look like the following:

Dim cmd As New SqlCommand("Select [Field1], [Field2], [Field3] [Field4 Added Dynamically] From [Table] Where [FieldX] = @parameter ")

If I have confused anyone or everyone please let me know and I will do my best to try an explain clearer.

MC

2
  • you can edit the commandtext property Commented Jul 27, 2016 at 19:03
  • You mean the 4th column you'll need is defined in runtime? In this case, you can have a variable Field4, and assign the column name to it. In your SQL command, just concatenate this variable accordingly. Commented Jul 27, 2016 at 19:04

1 Answer 1

1

Is this what you are looking for?

Dim DynamicField = "FieldToAdd"
Dim cmd As New SqlCommand("Select [Field1], [Field2], [Field3], " + DynamicField + " From [Table] Where [FieldX] = @parameter ")

I dont remember the exact VB syntax but you can use replace:

Dim DynamicField = "FieldToAdd"
Dim Sql = "Select [Field1], [Field2], [Field3], ##DynamicField## From [Table] Where [FieldX] = @parameter "
Sql = Sql.Replace("##DynamicField##", DynamicField)
Dim cmd As New SqlCommand(Sql)
Sign up to request clarification or add additional context in comments.

2 Comments

OMG!! Sweet thats exactly what i am looking for!! Thanks!!
Off the wall Question: If I have the SqlCommand saved as string could you dynamically add a field to the string somehow. I only ask this because i can already hear my boss asking this...

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.