I've got the following code to pull back a DataTable using a stored procedure and inputting a string parameter @JobNumbers, which is dynamically created string of job numbers (and therefore length is unknown):
using (SqlConnection connection = new SqlConnection(con)) { SqlCommand cmd = new SqlCommand("dbo.Mystoredprocedure", connection); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@JobNumbers", SqlDbType.VarChar, 4000); cmd.Parameters["@JobNumbers"].Value = JobNumber; SqlDataAdapter da = new SqlDataAdapter(cmd); connection.Open(); da.Fill(JobDetails); }
As you can see I've currently set the JobNumber parameter to a length of 4000, which should be enough to take around 500 job numbers and should be enough. However, there is the possibility that it may need more on the odd occasion. So, I was wondering, is there a way to set the parameter to the equivalent sql parameter type of nvarchar(max)?
I've had a look at various similar questions (What's the best method to pass parameters to SQLCommand?) but none specifically say whether you can (or can't) do this. Secondly, is it even necessary to do this if I set the @JobNumber parameter in the stored procedure to nvarchar(max) and therefore presumably I wouldn't need to set the length in C# at all? If I do this will this have potential performance issues as suggested in this question When should "SqlDbType" and "size" be used when adding SqlCommand Parameters??
The max size for a column of type NVARCHAR(MAX) is 2 GByte of storage. Since NVARCHAR uses 2 bytes per character, that's approx. 1 billion characters.
VARCHAR(MAX) or NVARCHAR(MAX) is considered as a 'large value type'. Large value types are usually stored 'out of row'. It means that the data row will have a pointer to another location where the 'large value' is stored...
SQL Server 2005 supports a new data type nvarchar(max). This is one of the new max datatypes that are to replace ntext, text, and image in a future version of SQL Server (according to SQL Server Books Online) but you should start using them now.
nvarchar max is for columns up to 2GB. So essentially it takes up more resources. You are better off using the nvarchar(50) if you know you aren't going to need that much space. each character is about 2 bytes so with 2 GB thats 1 billion characters...
This is how you explicitly set nvarchar(max):
cmd.Parameters.Add("@JobNumbers", SqlDbType.NVarChar, -1);
If you're really concerned with performance you might want to consider passing a table of integers: https://stackoverflow.com/a/10779593/465509
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With