通过VB添加SQL列的最简单方法

时间:2013-02-20 02:18:00

标签: sql vb.net visual-studio-2012 sql-server-2012

我想要做的是首先检查表中是否已存在某个列,如果没有添加它。我想通过visual basic实现这一点。如果有人花了一点时间发表评论并简要解释每一步,我会非常感激。

3 个答案:

答案 0 :(得分:0)

有两种方法可以确定列是否存在:尝试使用它并捕获错误(如果它不存在),或者从数据库中读取元数据,请参阅SQL Server: Extract Table Meta-Data (description, fields and their data types)

一旦您知道需要添加列,就可以使用ALTER TABLE命令将列添加到表中。

答案 1 :(得分:0)

这是vb.net脚本,用于检查如果列,如果不是,则创建它..

'''摘要 '''检查数据库中是否存在表。 “”” '''要检查的表名 '''要连接的连接字符串 '''可以使用Access或SQL '''

Public Function DoesTableExist(ByVal tblName As String, ByVal cnnStr As String) As Boolean
    ' For Access Connection String,
    ' use "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
    ' accessFilePathAndName

' Open connection to the database
Dim dbConn As New OleDbConnection(cnnStr)
dbConn.Open()

' Specify restriction to get table definition schema
' For reference on GetSchema see:
' http://msdn2.microsoft.com/en-us/library/ms254934(VS.80).aspx

Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = dbConn.GetSchema("Tables", restrictions)

If dbTbl.Rows.Count = 0 Then
    'Table does not exist
    DoesTableExist = False
Else
    'Table exists
    DoesTableExist = True
End If

dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()

结束功能

''” '''检查表中是否存在字段。 “”” '''要检入的表名 '''要检查的字段名称 '''要连接的连接字符串 “”” '''

公共函数DoesFieldExist(ByVal tblName As String,_                                ByVal fldName As String,_                                ByVal cnnStr As String)作为布尔值     '对于Access连接字符串,     'use“Provider = Microsoft.Jet.OLEDB.4.0; Data Source =”&     'accessFilePathAndName

' Open connection to the database
Dim dbConn As New OleDbConnection(cnnStr)
dbConn.Open()
Dim dbTbl As New DataTable

' Get the table definition loaded in a table adapter
Dim strSql As String = "Select TOP 1 * from " & tblName
Dim dbAdapater As New OleDbDataAdapter(strSql, dbConn)
dbAdapater.Fill(dbTbl)

' Get the index of the field name
Dim i As Integer = dbTbl.Columns.IndexOf(fldName)

If i = -1 Then
    'Field is missing
    DoesFieldExist = False
Else
    'Field is there
    DoesFieldExist = True
End If

dbTbl.Dispose()
dbConn.Close()
dbConn.Dispose()

结束功能

答案 2 :(得分:0)

    Dim connString As String = "Data Source=NameOfMachine\InstanceofSQLServer;Initial Catalog=NameOfDataBase;Integrated Security=True"
    Dim MyCol As String = "NameOfColumn"
    Dim MyTable As String = "[NameOfTable]" ' or "[Name Of Table]" use brackets if table name contains spaces or other illegal Characters
    Dim MySql As String = "IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.COLUMNS" & vbCrLf &
"WHERE TABLE_NAME = '" & MyTable & "' AND COLUMN_NAME = '" & MyCol & "')" & vbCrLf &
"BEGIN" & vbCrLf &
"ALTER TABLE [dbo]." & MyTable & " ADD" & vbCrLf & "[" & MyCol & "] INT NULL ;" & vbCrLf & "END"

    Try
        ' MsgBox(MySql)- this msg box shows the Query so I can check for errors- Not required for code.
        Dim dbConn = New SqlConnection(connString)' Note ConnString must be declared in the form class or within this Sub. Connstring is your connection string
        Dim dbCmd = New SqlCommand(MySql, dbConn)
        dbConn.Open()
        dbCmd.ExecuteNonQuery()
        'MessageBox.Show("Ready To Load Addendums")

        dbConn.Close()

    Catch ex As Exception
        MsgBox("We've encountered an error;" & vbCrLf & ex.Message)

    End Try