我在引用时检查是否存在SQL表中的条目?

时间:2015-06-11 14:28:47

标签: sql sql-server vb.net

顺便说一下,我是VB.NET的新手

我有一个表单,用户将输入信息,并将其添加到数据库中(如果该条目尚不存在。)。

数据库中有6列,将由用户输入信息的6个文本框填写,这些是名字,姓氏,家庭住址,城市,美国州和电话号码

Dim theQuery As String = "SELECT * FROM Salespeople WHERE FirstName=@FirstName AND LastName=@LastName AND HomeAddress=@HomeAddress AND City=@City"
Dim repeatChecker As SqlCommand = New SqlCommand(theQuery, myconnection)
repeatChecker.Parameters.AddWithValue("@First Name", TextBox1.Text)
        repeatChecker.Parameters.AddWithValue("@Last Name", TextBox2.Text)
        repeatChecker.Parameters.AddWithValue("@Home Address", TextBox10.Text)
        repeatChecker.Parameters.AddWithValue("@City", TextBox9.Text)
        repeatChecker.Parameters.AddWithValue("@US_State", TextBox11.Text)
        repeatChecker.Parameters.AddWithValue("@PhoneNumber", TextBox8.Text)
        Using reader As SqlDataReader = repeatChecker.ExecuteReader()
            If reader.HasRows Then
                ' User already exists
                MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
            End If
        End Using

我得到'nvarchar'附近有错误语法的错误,并且我必须声明变量@First Name。我不知道该改变什么。

1 个答案:

答案 0 :(得分:0)

假设你的列名有空格..

Dim theQuery As String = "SELECT * FROM Salespeople WHERE [First Name]=@FirstName AND [Last Name]=@LastName AND [Home Address]=@HomeAddress AND City=@City"
Dim repeatChecker As SqlCommand = New SqlCommand(theQuery, myconnection)
repeatChecker.Parameters.AddWithValue("@FirstName", TextBox1.Text)
        repeatChecker.Parameters.AddWithValue("@LastName", TextBox2.Text)
        repeatChecker.Parameters.AddWithValue("@HomeAddress", TextBox10.Text)
        repeatChecker.Parameters.AddWithValue("@City", TextBox9.Text)
        repeatChecker.Parameters.AddWithValue("@US_State", TextBox11.Text)
        repeatChecker.Parameters.AddWithValue("@PhoneNumber", TextBox8.Text)
        Using reader As SqlDataReader = repeatChecker.ExecuteReader()
            If reader.HasRows Then
                ' User already exists
                MsgBox("User Already Exist!", MsgBoxStyle.Exclamation, "Add New User!")
            End If
        End Using