创建带有SqlDataType,大小和值内联的Data.SqlClient.SqlParameter? [英] Create Data.SqlClient.SqlParameter with a SqlDataType, Size AND Value inline?

查看:108
本文介绍了创建带有SqlDataType,大小和值内联的Data.SqlClient.SqlParameter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以容纳多个SqlParameter对象的函数:

Public Shared Function RunSQL(sqlInput As String, Optional params As Data.SqlClient.SqlParameter() = Nothing) As String

目标基本上是能够根据需要调用该函数并创建参数.

不幸的是,似乎没有可用的构造函数允许我指定ValueSqlDbType,而不必也添加很多其他参数(我不需要).

所需的结果将类似于:

Dim myStr As String = RunSQL("spMyStoredProc", {New Data.SqlClient.SqlParameter("@FieldName", Data.SqlDbType.NVarChar, 50, "MyValue")})

很明显,由于不存在用于此目的的构造函数,所以我的问题基本上是询问是否有解决此问题的方法(如任何替代方法等),同时仍允许在函数调用中声明参数的便利性?/p>

我宁愿不必为了设置Value属性而事先声明所有参数.

解决方案

首先,您的代码会编译,但最后一个参数不是值,而是源列名称.

但是您可以使用With语句来分配Value:

Dim myStr As String = RunSQL("spMyStoredProc",
{
    New Data.SqlClient.SqlParameter("@FieldName", Data.SqlDbType.NVarChar, 50) With {.Value = "MyValue"}
})

请参阅: 对象初始化程序

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.

解决方案

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

这篇关于创建带有SqlDataType,大小和值内联的Data.SqlClient.SqlParameter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆