SQL参数是整数值还是dbnull传递给查询

时间:2016-05-02 10:17:18

标签: vb.net

无法让我的查询工作。我想将整数值或dbnull传递给我的查询,但在该表单中不起作用。在我的代码下面。

查询:

Using cmd As New SqlCommand("SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = @FK_Sentence_Id And FK_SubSection_Id = @FK_SubSection_Id And FK_SubSubKategorie_Id=@FK_SubSubKategorie_Id", con)

根据我需要的参数设置参数:

If _FK_SubSubKategorie_Id = 0 Then
                    cmd.Parameters.AddWithValue("@FK_SubSubKategorie_Id", DBNull.Value)
                Else
                    cmd.Parameters.AddWithValue("@FK_SubSubKategorie_Id", _FK_SubSubKategorie_Id)
                End If

如果_FK_SubSubKategorie_Id设置为DBNull,如下所示,我的查询应该改变一点而不是这一部分:

And FK_SubSubKategorie_Id=@FK_SubSubKategorie_Id", con)

And FK_SubSubKategorie_Id IS NULL", con)

正确的做法是什么?

这是整个SQL函数:

#Region "Check if connection already exist"
    Public Function CheckIfConnectionAlreadyExist(_FK_Sentence_Id As Integer, _FK_SubSection_Id As Integer, _FK_SubSubKategorie_Id As Integer) As Boolean
        Dim result As Boolean
        Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(String)).ToString()
        Using con As New SqlConnection(strcon)
            Using cmd As New SqlCommand("SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = @FK_Sentence_Id And FK_SubSection_Id = @FK_SubSection_Id And FK_SubSubKategorie_Id=@FK_SubSubKategorie_Id", con)
                cmd.CommandType = CommandType.Text

                cmd.Parameters.AddWithValue("@FK_Sentence_Id", _FK_Sentence_Id)
                cmd.Parameters.AddWithValue("@FK_SubSection_Id", _FK_SubSection_Id)
                If _FK_SubSubKategorie_Id = 0 Then
                    cmd.Parameters.AddWithValue("@FK_SubSubKategorie_Id", DBNull.Value)
                Else
                    cmd.Parameters.AddWithValue("@FK_SubSubKategorie_Id", _FK_SubSubKategorie_Id)
                End If
                con.Open()
                Dim o As Integer = cmd.ExecuteScalar()
                If o > 0 Then
                    result = True
                Else
                    result = False
                End If
                con.Close()
            End Using
        End Using
        Return result
    End Function
#End Region

1 个答案:

答案 0 :(得分:1)

只需创建一个查询字符串,这两个条件具有共同点,然后将其更改为_FK_SubSubKategorie_Id。然后创建命令:

Dim qry as String = "SELECT COUNT(*) FROM tbSuSubSections_Sentences WHERE FK_Sentence_Id = @FK_Sentence_Id And FK_SubSection_Id = @FK_SubSection_Id And FK_SubSubKategorie_Id {0}"

If _FK_SubSubKategorie_Id = 0 Then
  qry = string.Format(qry," IS NULL")
Else
  qry = string.Format(qry, "=@FK_SubSubKategorie_Id"
End if

Using cmd As New SqlCommand(qry, con)
  ...
相关问题