Best practice for returning type from SQL Server to ExecuteScalar?
-
13-11-2019 - |
Question
In C# SqlCommand - ExecuteScalar
is :
private object CompleteExecuteScalar(SqlDataReader ds, bool returnSqlValue)
now let's go to SQL Server.
If I want to return a value from the select (which goes to ExecuteScalar
), e.g. :
if record already exists select `-1`
else select `0`
Question :
what is the preferred (by best practices) type for returning from SQL Server in order to reduce the amount of casting & tostring() in C#:
if exists(select ....) select '-1' -- string
or
if exists(select ....) select -1 -- int
Solution
You are returning number so int
is preferable here by meaning.
Futher more, when parsing error in C# code you will be albe to do somethinng like:
enum Error { NO_ERROR = -1, ERROR 1 };
....
Error e = (Error)cmd.ExcecuteScalar();
Which is pretty clean and self explaining code as oposite to parsing result to int, or comparing string values.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow