Solved

VB.net Check if a column exists in a SQL Table

Posted on 2014-11-11
5
553 Views
Last Modified: 2014-11-11
Hi
What VB.net code would I use to check if a column exists in a SQL table?
Thanks
0
Comment
Question by:murbro
5 Comments
 
LVL 2

Expert Comment

by:Pratik Makwana
ID: 40434702
This function is check if column is exist or not.....

Dim oField ' As ADODB.Field
      Dim oRecordset ' As ADODB.Recordset
      Dim oConn ' As ADODB.Connection
      Dim nameToCheck
      Dim nameExists
      
      ' The column name you're looking for
      nameToCheck = "ID"
      nameExists = false
      
      ' Create connection
      Set oConn = Server.CreateObject("ADODB.Connection")
      oConn.Open "YourConnectionString"
      
      Set oRecordset = oConn.Execute("SELECT * FROM YourTable")
      
      For Each oField In oRecordset.Fields
            If oField.Name = nameToCheck Then
                  nameExists = True
                  Exit For
            End If
      Next
      
      oRecordset.Close()
      oConn.Close()
      Set oConn = Nothing
      Set oRecordset = Nothing
      
      Response.Write("Field " & nameToCheck & " found: " & nameExists)
0
 
LVL 69

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 40434836
It is better not to use ADODB in a .Net application!

Do you already have the structure in a DataSet/DataTable?

If you want to go pure SQL, you could use this:
SELECT T.name AS TableName, C.name AS ColumnName 
FROM sys.tables AS T
INNER JOIN sys.columns AS C
ON C.object_id = T.object_id
WHERE T.name = 'RefPrefix'
AND C.name = 'Code2'

Open in new window

0
 
LVL 17

Expert Comment

by:OriNetworks
ID: 40435049
I think Eric has the best answer here where t.name is the table name you are checking and C.name is the column name you are checking for. If the column exists, it will return one row. If it does not exist, no rows will be returned.
0
 
LVL 27

Expert Comment

by:Ark
ID: 40436608
    Public Shared Function ColumnExists(ByVal tableName As String,
                                        ByVal columnName As String,
                                        ByVal conn As SqlClient.SqlConnection) As Boolean
        Dim strSQL As String = "SELECT COUNT(*) FROM information_schema.columns " & _
                               "WHERE table_schema = 'dbo' " & _
                               "AND table_name = '" & tableName & "'" & _
                               "AND column_name = '" & columnName & "';"
        Using cmd As New SqlClient.SqlCommand(strSQL, conn)
            Return CBool(cmd.ExecuteScalar)
        End Using
    End Function

Open in new window

Dim bExists As Boolean
Using conn As New SqlClent.SqlConnection(YourConnectionStringHere)
    conn.Open()
    bExists = ColumnExists(YourTableName, YourColumnName, conn)
    conn.Close()
End Using

Open in new window

0
 

Author Closing Comment

by:murbro
ID: 40436653
Thanks
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now