vb.net sql检查表中是否存在值并将结果转换为变量

时间:2019-02-06 14:29:59

标签: sql sql-server vb.net

我正在创建一个简单的关系数据库系统,以确保不保存重复的数据。我创建了一大段代码来检查所选表中是否已经存在 Album 的值:

If Album IsNot Nothing Then 'checks if ALBUM exists
    ALBUM_CHECK = New SqlCommand("SELECT ALBUM_ID FROM ALBUM_DB WHERE NAME=(@NAME)", SQLcon)
    ALBUM_CHECK.Parameters.AddWithValue("@NAME", Album)
    If ALBUM_CHECK.ExecuteScalar IsNot Nothing Then
        album_Exist = True
    Else
        album_Exist = False
    End If
End If

但是这将返回错误:

  

System.Data.SqlClient.SqlException:'数据类型text和nvarchar在等于运算符中不兼容。'

关于如何解决这个问题的任何想法?

我认为,如果返回的值为null,则不允许我读取。感谢所有帮助!

2 个答案:

答案 0 :(得分:1)

来自the documentation of SQL Server 2017

  

重要!在未来版本的SQL Server中将删除ntexttextimage数据类型。避免在新的开发工作中使用这些数据类型,并计划修改当前使用它们的应用程序。改用nvarchar(max)varchar(max)varbinary(max)

我建议将此列的数据类型更改为varchar(max),它在存储方面具有相同的容量,并且受到此RDBMS的正确支持。

答案 1 :(得分:0)

对于相册而言,文本是非常差的选择。符合注释和解释。

Private Sub OPCode()
    Dim Album As String = ""
    Dim albumExist As Boolean
    If String.IsNullOrEmpty(Album) Then
        Return
    End If
    'Using blocks ensure that your database objects are not only closed but disposed.
    'The disposal is important because they can contain unmanaged objects.
    Using SQLcon As New SqlConnection("Your connection string")
        'If Exists is a good method for large tables because it stops as soon
        'as it finds a match.
        Using ALBUM_CHECK As New SqlCommand("If Exists (SELECT 1 FROM ALBUM_DB WHERE NAME = @NAME) Select 1 Else Select 0;", SQLcon)
            'Using .Add instead of .AddWithValue tells the database what kind of
            'data we are sending. Without this we have no control over what ADO
            'decides to sent to the database.
            ALBUM_CHECK.Parameters.Add("@NAME", SqlDbType.NVarChar).Value = Album
            'The query will only return a 0 or a 1.
            SQLcon.Open
            albumExist = CBool(ALBUM_CHECK.ExecuteScalar())
        End Using
    End Using
End Sub