I want to create a stored procedure (in SQL Server 2008 R2) that will update a record in a table based on a PK table.
A stored proc will have, for example, four parameters:
@ID int, @Name nvarchar(50), @Email nvarchar(80), @Phone nvarchar(20)
How can I determine if the caller of a stored proc passes NULL for one (or more) parameters, or if the caller has not passed anything for one (or more) parameters?
C # call example:
Caller points to NULL for @Phone :
using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "EditPerson"; cmd.Parameters.AddWithValue("@ID", id); cmd.Parameters.AddWithValue("@Name", 'Frank'); cmd.Parameters.AddWithValue("@Email", ' frank@frank.com '); cmd.Parameters.AddWithValue("@Phone", DBNull.Value); DatabaseManager.instance.ExecuteScalarQuery(cmd); }
Caller ignores the @Phone parameter:
using (SqlCommand cmd = new SqlCommand()) { cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.CommandText = "EditPerson"; cmd.Parameters.AddWithValue("@ID", id); cmd.Parameters.AddWithValue("@Name", 'Frank'); cmd.Parameters.AddWithValue("@Email", ' frank@frank.com '); DatabaseManager.instance.ExecuteScalarQuery(cmd); }
What I'm trying to do here is that if the caller explicitly specifies a NULL value for the parameter, I am updating the record with the NULL value. However, if the user explicitly ignores passing the parameter, then the UPDATE query will save the field / column value that is already set for a particular record (i.e., the query will NOT update that particular column).
I assume that I can specify default values โโthat can safely be assumed that the caller will never use - something like this:
@ID int, @Name nvarchar(50) = 'NameIsUndefined', @Email nvarchar(80) = 'EmailIsUndefined', @Phone nvarchar(20) = 'PhoneIsUndefined'
Then in the saved proc I can check the values โโof undefined - if the vars parameter is still set to NameIsUndefined , EmailIsUndefined and / or PhoneIsUndefined , then I can safely assume that the caller did not explicitly specify values โโfor these parameters. Is this the only way to achieve my goal?