vb.net - 动态生成SQL Command对象

时间:2013-01-17 16:32:03

标签: vb.net

有些人可以帮助我们如何动态生成命令对象。请参阅下文 - 我需要将数据库名称和表名称传递给应该返回该表中行数的函数。我很难写这个查询。查看我正在尝试的代码

        Using _Conn As New SqlConnection(_ConnString)
            _SQLCommand = New SqlCommand()
            _SQLCommand.CommandText = "Select count(*) from " & _
            "lvar_Database " + ".dbo." + lvar_Table
            _SQLCommand.Parameters.Add(New SqlParameter("@Database_Name", SqlDbType.NVarChar))
            _SQLCommand.Parameters.Add(New SqlParameter("@Table_Name", SqlDbType.NVarChar))
            _SQLCommand.Parameters("@Database_Name").Value = lvar_Database
            _SQLCommand.Parameters("@Table_Name").Value = lvar_Table
            Try
                _Conn.Open()
                GetNumberofRows = Convert.ToInt32(_SQLCommand.ExecuteScalar())
            Catch ex As Exception
            End Try
        End Using

此致

1 个答案:

答案 0 :(得分:1)

您不需要命令参数。只需使用db和表名动态组装查询:

    Using _Conn As New SqlConnection(_ConnString)
        _SQLCommand = New SqlCommand()
        _SQLCommand.CommandText = _
            "Select count(*) from " + _
            lvar_database + _
            ".dbo." + _
            lvar_Table

        Try
            _Conn.Open()
            GetNumberofRows = Convert.ToInt32(_SQLCommand.ExecuteScalar())
        Catch ex As Exception
        End Try
    End Using