2

What is the simplest way to store a string into variable. For example

How do I store something into @bleh variable.

SqlCommand stej = new SqlCommand("SELECT COUNT(*) FROM test3 WHERE PostID = @bleh", con);

@bleh variable has to be set somehow. I tried replacing @bleh with a 100,abc,da, etc. And it works. But my bleh variable will change with the loop.

Thanks

1
  • 2
    When do you need to change the value of the variable? on the sql code? or on the .net code? Commented Jan 12, 2011 at 14:16

2 Answers 2

3

These are called Parameters.

To set the value:

stej.Parameters.AddWithValue("@bleh", postId);

(There are more options, if you need to explicitly control the datatype, etc)

A single Parameter can only contain one value though. If you wish to pass multiple values, you would need multiple parameters.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a sql parameter

 using ( SqlConnection conn = new SqlConnection( "connection string" )
    {
      conn.Open();

      string selstr = "SELECT COUNT(*) FROM test3 WHERE PostID = @bleh";
      SqlCommand cmd = new SqlCommand( selstr, conn );
      SqlParameter name = cmd.Parameters.Add( "@bleh", SqlDbType.NVarChar, 255 );
      name.Value = "value";
      int count = cmd.ExecuteScalar();
      //Do you stuff
   }

Comments

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.