Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of SqlCommand Parameter & CommandText declaration matter?

Tags:

c#

sql-server

I'm using the SqlCommand object to read from/write to my database. I know that using SQL commands like below could lead to trouble:

Select * from myTable where tableId = '" + tableID + "'";

Instead, I've been using the preferred method of commands like:

Select * from myTable where tableId = @Table_ID";

Then create my parameters:

sqlCommand.Parameters.Add("@Table_ID", SqlDbType.VarChar, 50).Value = tableID;

I have two questions:

  1. Is the order that I add my parameters to the SqlCommand object important?

  2. Do I need to add my SqlCommand.CommandText string before I add my parameters?

I've always added my CommandText first and then added my parameters in order that they are used in the SQL string, but there are times where I would like to select from two different SQL strings (example: insert vs. update), but then add all the parameters after the "If" statement instead of nesting them inside it.

like image 880
Jason Hall Avatar asked Oct 15 '25 14:10

Jason Hall


1 Answers

  1. No, the parameters do not need to be added in the order that they appear in the text, as long as they are named parameters

  2. It's not necessary to add the CommandText to the SqlCommand before the parameters

like image 174
Theb Avatar answered Oct 17 '25 05:10

Theb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!