我有一个对象(Results_DataColumn
),该对象保存数据提供者服务器上每个Survey的列名。现在,我必须使用此列信息创建一个表,因此,如果Results_DataColumn
对象持有(1)Name and (2)City
,我想使用Columns 1 ID, 2 Name, 3 City
在自己的Sql Server上创建一个表。我写的代码是:
Public Class TableCreator
Public Shared Sub CreateTable(ByRef myColumnInformation As Results_DataColumn, ByVal tableName As String)
Dim conStr As String = "Server=NB01035;Database=DB_Import;Trusted_Connection=true"
Using con As SqlConnection = New SqlConnection(conStr)
Using sqlCom As New SqlCommand
With sqlCom
.Connection = con
.CommandType = CommandType.Text
.CommandText = queryBuilder(myColumnInformation, tableName)
End With
Try
con.Open()
sqlCom.ExecuteNonQuery()
Catch ex As SqlException
Console.WriteLine(ex.Message.ToString(), "Error Message")
End Try
End Using
End Using
End Sub
Public Shared Function queryBuilder(ByRef myColumnInformation As Results_DataColumn, ByVal tableName As String) As String
Dim query As StringBuilder = New StringBuilder
query.Append("IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = [")
query.Append(tableName)
query.Append("] DROP [")
query.Append(tableName)
query.Append("] BEGIN CREATE TABLE [")
query.Append(tableName)
query.Append("] ( ID int identity(1,1) not null, ")
For i As Integer = 0 To myColumnInformation.results.Count - 1
query.Append(myColumnInformation.results(i).questionCode.ToString)
query.Append(" VARCHAR(MAX)")
query.Append(", ")
Next
If myColumnInformation.results.Count > 1 Then
query.Length -= 2
End If
Console.WriteLine(query.ToString)
query.Append(")")
Console.WriteLine(query.ToString)
Return query.ToString
End Function
End Class
它一直运行,但没有在服务器上创建表,我只是不知道为什么。创建的SQL查询看起来不错。有人可以帮助我吗?