Click here to Skip to main content
15,908,166 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to check sql server table and their column through vb.net code
Posted
Comments
Sandeep Mewara 19-Mar-11 3:10am    
"Check"? Elaborate.

1 solution

Below code will provide you the table name of the SQL server for the current database.

You just need to pass required parameter to connect to the database.

VB
Protected Sub getTables()
       Dim dbconn As SqlConnection
       Dim sql As String
       Dim Command As SqlCommand
       dbconn = New SqlConnection("server=" & txtserver.Text.Trim & ";uid=" & txtuid.Text.Trim & ";pwd=" & txtpwd.Text.Trim & ";database=" & txtdatabase.Text.Trim & "")
       dbconn.Open()
       sql = "SELECT * FROM sys.tables where type='U'"
       Command = New SqlCommand(sql, dbconn)
       Dim dtAdapter As New SqlDataAdapter
       Dim dtTable As New DataTable
       dtAdapter.SelectCommand = Command
       dtAdapter.Fill(dtTable)
       chkTable.DataSource = dtTable
       chkTable.DataTextField = "name"
       chkTable.DataBind()
       Dispose()

   End Sub


So from above code, you will have a all SQL table list in the DataTable object chkTable.

Try out below code for getting individual table column name.

VB
For Each item As ListItem In chkTable.Items
                If item.Selected Then
                    dbconn.Open()
                    sql = "SELECT * FROM " & item.Text
                    Command = New SqlCommand(sql, dbconn)
                    Dim dtAdapter As New SqlDataAdapter
                    Dim dtTable As New DataTable
                    dtAdapter.SelectCommand = Command
                    dtAdapter.Fill(dtTable)
                    Dispose()
                    dbconn.Close()
                    'add your custom logic here for what you need to do with all the columns
                End If
            Next


Hope it helps.
 
Share this answer
 
Comments
Dalek Dave 19-Mar-11 6:15am    
Good Answer.
That's Aragon 19-Mar-11 6:42am    
Thank you DD :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900