Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Passing nulls and uniqueidentifier parameters to stored procedure from C#

$
0
0

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.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>