问题
I have a function which can take a number of SqlParameter
objects:
Public Shared Function RunSQL(sqlInput As String, Optional params As Data.SqlClient.SqlParameter() = Nothing) As String
The aim is basically being able to call the function and create the parameters if needed, as needed.
Unfortunately, there do not appear to be any constructors available that will allow me to specify the Value
as well as the SqlDbType
without having to add lots of additional parameters (that I do not need) as well.
The desired outcome would be something like:
Dim myStr As String = RunSQL("spMyStoredProc", {New Data.SqlClient.SqlParameter("@FieldName", Data.SqlDbType.NVarChar, 50, "MyValue")})
Obviously as the constructor for this does not exist, my question is basically to ask whether or not there is any way around this, as in any alternative, etc whilst still allowing the convenience of declaring the parameters in the function call?
I'd rather not have to declare all of my parameters beforehand just to set the Value
property.
回答1:
First, your code compiles but the last parameter is not the value but the source-column-name.
But you could use the With
statement to assign the Value
:
Dim myStr As String = RunSQL("spMyStoredProc",
{
New Data.SqlClient.SqlParameter("@FieldName", Data.SqlDbType.NVarChar, 50) With {.Value = "MyValue"}
})
See: Object Initializers
来源:https://stackoverflow.com/questions/19789562/create-data-sqlclient-sqlparameter-with-a-sqldatatype-size-and-value-inline