简体   繁体   中英

VB.Net IIf function in adding SqlParameter

I am rewriting this long INSERT statement and parameters used to look like this:

    cmd.Parameters.AddWithValue("@Website", General.fnSQLNullValues(tWebsite.Text))

Where General.fnSQLNullValues is this:

        Public Shared Function fnSQLNullValues(ByVal sValue As Object, Optional ByVal Len As Integer = 999999) As Object
            If sValue Is Nothing Then Return DBNull.Value
            fnSQLNullValues = IIf(sValue.ToString.Length = 0, DBNull.Value, Left(sValue.ToString(), Len))
        End Function

I don't like this at all , and it seems to be alot of code all to do just this,

       cmd.Parameters.AddWithValue("@Website" , If(tWebsite.Text , DBNull.Value))

from my understanding , that one line of code there DBNull.Value will replace tWebsite.Text as the value if tWebsite.Text is null or not accepted and it seems to me to do the same thing as the other function in General. Is this correct and is one way any better then the other?

Also , I get Warning : "Cannot Infer Common Type; Object Assumed" from the second way , but it seems to me that the first way was using a generic object anyways , so I do not know if I should just ignore this warning

Strings are a little tricky when working with database parameters in code. If you have an empty string, it will pass an empty string value for insertion. However, if you set you set your string to a value of Nothing, it will insert a NULL value into the database. Otherwise it will set an empty string.

Ideally, you'd have some kind of business layer on top of your data layer that will check your tWebsite.Text value and either pass in Nothing or the Text value to your function that sets up the parameters. This is slightly different that your first code example above. That way your data layer only has to execute the following command:

cmd.Parameters.AddWithValue("@Website" , valueWebsite))

...and no hassle is necessary.

For other data types (such as integers, decimals, etc.), check out the Nullable Types and work with them. They make things really easy to work with. By default they initialize to Nothing, so if you don't assign it a value (from your input boxes) the value stays Nothing and will do a proper NULL insert into the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM