Create Data.SqlClient.SqlParameter with a SqlDataType, Size AND Value inline?

╄→гoц情女王★ 提交于 2019-12-11 20:29:36

问题


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

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