Parameterized query error: Must declare scalar variable

Asked

Viewed 949 times

1

I am aware of the existence of this question: Error in previous "Must declare the scalar variable"

But it does not solve my problem. My situation is as follows:

I have a common sql query:

select id from USUARIOS where login = @txtlogin and password = @txtpassword

This is my object SqlCommand:

conn = new SqlConnection(ConnectionString);
 conn.Open();
var com = new SqlCommand(command, conn);

I create the SqlCommand, the connection is opened normally, and I add the parameters like this:

SqlParameter param = new SqlParameter();
param.ParameterName = "@txtlogin";
param.Value = "teste";
//command é o meu SqlCommand devidamente inicializado
command.Parameters.Add(param);

param = new SqlParameter();
param.ParameterName = "@txtsenha";
param.Value = "teste";
//command é o meu SqlCommand devidamente inicializado
command.Parameters.Add(param);

However, when executing the query, it gives me the error:

Must declare the scalar variable @txtlogin

What I might be doing wrong?

  • 2

    Do a [mcve], missing important snippets becomes difficult to answer.

1 answer

1

There are two possibilities here:

  • You use Stored Procedures? If yes, change the value of the property CommandType of your SqlCommand for CommandType.StoredProcedure. Thus:
com.CommandType = CommandType.StoredProcedure;
  • You do not use Stored Procedures? In this case, you need to declare each variable you are going to use in the query you are going to pass to the database. Your complete query would look like this:
DECLARE @txtlogin nvarchar(20), @txtsenha nvarchar(20)
SELECT id FROM USUARIOS WHERE login = @txtlogin AND password = @txtpassword

Browser other questions tagged

You are not signed in. Login or sign up in order to post.