views:

107

answers:

2

I am getting an SQLException "Operand type clash: int is incompatible with uniqueidentifier" when I am trying to execute the below stored procedure from C# code.

create proc sp_Get_Allfields_Account_Public
@username varchar(20),
@password varchar(20),
@acc_num UniqueIdentifier out,
@cust_name varchar(20) out,
@balance float out
as
select @acc_num=acc_num,@cust_name=cust_name,@balance=balance from Account_Public where username=@username and password=@password

C# code is as follows

cmd = new SqlCommand("sp_Get_Allfields_Account_Public", con);
               cmd.CommandType = CommandType.StoredProcedure;

               // Add Input Parameters
               cmd.Parameters.AddWithValue("@username", username);
               cmd.Parameters.AddWithValue("@password", password);   

               // Add output parameters
               cmd.Parameters.AddWithValue("@acc_num", SqlDbType.UniqueIdentifier);
               cmd.Parameters["@acc_num"].Direction = ParameterDirection.Output;

               cmd.Parameters.AddWithValue("@cust_name", SqlDbType.VarChar);
               cmd.Parameters["@cust_name"].Direction = ParameterDirection.Output;

               cmd.Parameters.AddWithValue("@balance", SqlDbType.Float);
               cmd.Parameters["@balance"].Direction = ParameterDirection.Output;

               cmd.ExecuteNonQuery();

Table definition

create table Account_Public
(
acc_num uniqueidentifier,
cust_name varchar(20),
username varchar(20),
password varchar(20),
balance float
)
A: 

This may seem a bit redundant, but are you sure that the data type of column [Account_Public].[acc_num] is actually uniqueidentifier and not int?

Try this instead:

cmd = new SqlCommand("select @acc_num=acc_num,@cust_name=cust_name,@balance=balance from Account_Public where username=@username and password=@password", con);
cmd.CommandType = CommandType.Text;

with the same parameters. Do you get the same error?

Also, I strongly recommend that you specify explicit sizes on all the char parameters. It's not so important for the input parameters, but it's very important for the output ones.

Christian Hayter
+7  A: 

It's because you're calling AddWithValue, then passing the value as the enum (which is interpreted as an int).

cmd.Parameters.AddWithValue("@acc_num", SqlDbType.UniqueIdentifier); 

Use a different method (probably just Add).

ck
I think this is it. Just spotted the WithValue part.
Henk Holterman
Tried Add method but this time I get the exceptionString[3]: the Size property has an invalid size of 0.
Nadeem
@Nadeem You need to specify a size for your varchar output variable, otherwise it defaults to 0, and you can't have an nvarchar(0).
Ben Robinson