Search code examples
c#stored-proceduresado.netnvarcharsqlparameter

When calling a stored procedure with ADO.NET, how do I tell what parameter types the database actually used?


I have a stored procedure call in C#. It uses ADO.NET to call the stored procedure that is on my SQL Server. Despite knowing that one of the parameters of the stored procedure on the server is VARCHAR(120), I used AddWithValue to add it to my parameter collection in C# and that has concluded that the string parameter used in C# should be translated to a SqlDbType of NVARCHAR. How do I tell if the server has used the NVARCHAR type or the VARCHAR type? I'm getting mixed messages regarding if ADO.NET is smart enough to read the correct parameter type from the server and I would like to test this empirically.

My current crude solution was as follows:

  1. Take a character that does not exist in VARCHAR, e.g. ǹ i.e. 'Latin Small Letter N With Grave'.
  2. Observe that SQL Server translates SELECT ǹ to ?.
  3. Write a query that returns values when ? is fed to it.
  4. Feed said query ǹ.
  5. Observe that the query has acted as if I fed it ?.
  6. Conclude that SQL has used VARCHAR even though I gave it NVARCHAR.

Solution

  • that has concluded that the string parameter used in C# should be translated to a SqlDbType of NVARCHAR. How do I tell if the server has used the NVARCHAR type or the VARCHAR type? I'm getting mixed messages regarding if ADO.NET is smart enough to read the correct parameter type from the server and I would like to test this empirically.

    There is no such functionality. ADO.Net does not query anything from the server, it just sends whatever you tell it. If that has defaulted to nvarchar then that is what will be sent. This is why you should always specify the data types and lengths/precision/scale.

    Having said that, in the case of stored procedures, the server will then convert the data back to the original type to fit into the parameter declaration, with a slight overhead, and possible loss of precision or characters etc.