Parameterized query error: Must declare scalar variable [closed]

1

I am aware of the existence of this question: Procedure error " 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 SqlCommand , the connection opens 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 I run the query, it gives me the error:

  

Must declare the scalar variable @txtlogin

What can I be doing wrong?

    
asked by anonymous 10.07.2017 / 20:30

1 answer

1

There are two possibilities here:

  • Do you use Stored Procedures? If yes, change the value of the CommandType " of your SqlCommand to CommandType.StoredProcedure . Thus:
com.CommandType = CommandType.StoredProcedure;
  • Do not you use Stored Procedures? In this case, you need to declare each variable that will be used in the query that will be passed to the bank. Your complete query would look like this:
DECLARE @txtlogin nvarchar(20), @txtsenha nvarchar(20)
SELECT id FROM USUARIOS WHERE login = @txtlogin AND password = @txtpassword
    
24.07.2017 / 13:28