Conrad Jagger
Conrad Jagger

Reputation: 643

vb.net - Generate SQL Command object dynamically

Can some please help how to dynamically generate command object. See below - I need to pass database name and table name to the function which should return number of rows in that table. I'm struggling to write this query. See code which i'm try

        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

Regards

Upvotes: 2

Views: 807

Answers (1)

Paul Sasik
Paul Sasik

Reputation: 81429

You do not need command parameters for this. Just assemble your query dynamically with the db and table name:

    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

Upvotes: 1

Related Questions