質問

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??

役に立ちましたか?

解決

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top