I need to call a TSQL stored procedure from C#. It takes one parameter which may be null or a uniqueidentifier.
My code is:
using (SqlConnection Con = new SqlConnection(connectionString)) { SqlCommand sqlCommand = new SqlCommand("GetList", Con); sqlCommand.CommandType = CommandType.StoredProcedure; SqlDataAdapter Da = new SqlDataAdapter(sqlCommand); SqlParameter MyId = sqlCommand.Parameters.Add("MyId", SqlDbType.UniqueIdentifier); MyId.Value = new Guid(sSubjectId); MyId.Direction = ParameterDirection.Input; Da.Fill(ds); }
The stored procedure works for nulls in Management Studio but I am unsure how to pass it the uniqueidentifier; when I try to do so the sproc fails.
From C#:
When MyId = an actual value (string converted to Guid), I get error "Arithmetic overflow error converting expression to data type nvarchar."
When MyID = null, I get error "Value cannot be null.\r\nParameter name: g".
Note - when I execute the program with the query hardcoded in as:
sQuery = "select NewId, Title from dbo.myTable Where MyCol = CONVERT(uniqueidentifier,'"+ sMyGuid + "')";
it works perfectly when sMyGuid is a string that can be converted to a Guid.
Can someone explain how to pass nulls and how to pass uniqueidentifiers to a stored procedure?
Thank you.