-2

I need help in retrieving parameters in SQL query (not stored procedure) and their data types in C#. Here is a sample query.

Declare @param1 int
Declare @param2 varchar(255)

Select * 
from tablenanme 
where col1 = @param1 and col2 = @param2

How can I also assign these values dynamically in C#

I've tried but I can really figure it out

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Kamweti C
  • 19
  • 6
  • Where is your C# code? What attempt have you made and what specifically didn't work? What do you mean by *retrieve* parameters? Do you mean that you're trying to *add* parameters to your query? Please clarify the question. – David Oct 26 '21 at 14:40
  • I'm sure I saw this question the other day... – Thom A Oct 26 '21 at 14:40
  • 1
    I did... How is this different from your [last question](https://stackoverflow.com/q/69695780/2029983)? – Thom A Oct 26 '21 at 14:41
  • 1
    Does this answer your question? [C# and SQL get declared parameters Data type and add the parameters dynamically](https://stackoverflow.com/questions/69695780/c-sharp-and-sql-get-declared-parameters-data-type-and-add-the-parameters-dynamic) Don't repost the same question again – Charlieface Oct 26 '21 at 15:03

1 Answers1

1

Don't declare local variables in the batch. Instead, add parameters/values to the command object:

var command = new SqlCommand("Select * from tablenanme where col1=@param1 and col2=@param2", connection);
command.Parameters.Add("@param1", SqlDbType.Int).Value = col1Value;
command.Parameters.Add("@param2", SqlDbType.VarChar, 255).Value = co2Value;
Dan Guzman
  • 43,250
  • 3
  • 46
  • 71