How to create NVarchar(max) Sqlparameter in C#? [duplicate]

余生颓废 提交于 2019-12-17 16:45:08

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/21087950/how-to-create-nvarcharmax-sqlparameter-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!