Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat to use for Size argument in Database.AddOutParameter when returning a string?
    text
    copied!<p>I'm getting a string as an output parameter, and need to know what to set for the Size argument in the call to AddOutParameter.</p> <p>I know I could just use some huge number, like int.MaxValue, but want to know best practices.</p> <p>In SQL Server, the column is actually a uniqueidentifier type. The T-SQL statement being executed inserts a record, and then sets some output variables to the ID and GUID of the newly inserted records. This is the actual code I'm using, but with variable names changed.</p> <pre><code>database.AddOutParameter(cmd, "@someInt", DbType.Int32, 0); database.AddOutParameter(cmd, "@someString", DbType.String, 0); database.ExecuteNonQuery(cmd); someInt = (int)database.GetParameterValue(cmd, "@someInt"); someString = database.GetParameterValue(cmd, "@someString").ToString(); </code></pre> <p>When executed, I get the following error...</p> <p>System.InvalidOperationException: String[2]: the Size property has an invalid size of 0.</p> <p>So it's obvious to me that you can't just use a size of 0 with a string output parameter. You can do that with an Int32 output parameter, but I guess a string needs a valid size. So what is the best practice for setting the size? Can it just be a huge size without affecting performance at all? Can I just set it to int.MaxValue or something? Is there any constant that can be used here; (didn't see any String.MaxValue - you can probably tell I'm new to C#, with a Java background).</p> <p>Should I find out what the max size of a uniqueidentifier column is and set the size to that? What about if I'm doing the same thing for a VARCHAR or NVARCHAR column?</p> <p>I wish the framework would just do it for me; I don't want to specify a size for every string that I get as output. Anyone have any suggestions here for best practice?</p> <p>I've read the posts below, as well as MSDN documentation, but there's not really a best practices answer to this that I've found yet.</p> <p><a href="https://stackoverflow.com/questions/3108881/addoutparameter-non-magic-number-way-of-finding-length-of-dbtype-int32">AddOutParameter - non-magic number way of finding length of DBType.Int32</a></p> <p><a href="https://stackoverflow.com/questions/4948051/read-varbinarymax-from-sql-server-to-c-sharp">Read VARBINARY(MAX) from SQL Server to C#</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload