I am trying to get an insert/return primary key SQL query to run.
The query ends up looking like this:
declare @userid as integer;
insert into users (username,emailaddress,passwordhash,salt) values
(@username,@email,@password,@salt);
set @userid=scope_identity();
insert into groups (name,userid) values ('somegroup',@userid);
select @userid;
This simply goes into the SqlCommand.CommandText field. So this is executed as a single query
I then add the parameters like this: (cmd is a SqlCommand object)
cmd.Parameters.Add(new SqlParameter("@email",user.EmailAddress));
cmd.Parameters.Add(new SqlParameter("@username",user.Username));
cmd.Parameters.Add(new SqlParameter("@salt",user.Salt));
cmd.Parameters.Add(new SqlParameter("@password", user.PasswordHash));
I then execute the query with ExecuteScalar(); It will throw an error at this point though saying the parameter @email doesn’t exist.
How do I fix this problem?
I’ve figured it out. If you send give null as the value of a parameter, it won’t actually be added. So the solution(for me anyway, for you, it may involve
DBNull) was to convert nulls into empty strings as so: