|
本帖最后由 ericxzhou 于 2023-7-4 16:57 编辑
Excel ADO 毕竟没有专业SQL软件强大,我写了一个自定义函数,可以根据Excel表格自动生成建表语句,供参考:
- Function SQLCTable(ByVal rng As Range, ByVal tblName As String) As String
- 'rng为表的范围包含表头
- 'tblName为表名,用双引号包围
- Dim i%, j%, arr, str$, str1$, str2$
- arr = rng
- For i = 1 To UBound(arr, 2)
- str1 = str1 & "," & arr(1, i) & typeJudge(arr(2, i))
- '需确保表头下第一行都有数据,第一行如为小数类型小数点后需有数字,否则无法判断列的数据类型
- Next
- str1 = "CREATE TABLE " & tblName & " (" & Right(str1, Len(str1) - 1) & ");" & Chr(10)
- For i = 2 To UBound(arr)
- For j = 1 To UBound(arr, 2)
- Select Case VarType(arr(i, j))
- Case 7
- str = str & "," & "'" & Format(arr(i, j), "yyyy-m-d") & "'"
- '注意SQL存储日期数据的格式,不能用#号包围
- Case 8
- str = str & "," & "'" & arr(i, j) & "'"
- Case 0, 1, 10
- str = str & ",NULL"
- '如需改为0,需判断字段类型,否则会发生插入不匹配报错
- Case 2, 3, 4, 5, 6
- str = str & "," & arr(i, j)
- Case Else
- str = str & "," & "'" & arr(i, j) & "'"
- End Select
- Next
- str2 = str2 & ")," & Chr(10) & "(" & Right(str, Len(str) - 1)
- str = ""
- Next
- SQLCTable = str1 & "INSERT INTO " & tblName & " VALUES " & Right(str2, Len(str2) - 2) & ");"
- End Function
- Function typeJudge(ByVal inputData As Variant) As String
- Select Case VarType(inputData)
- Case 7
- typeJudge = " DATE"
- Case 8
- typeJudge = " VARCHAR(100)"
- '100为最大长度,如不够可调
- Case 2, 3, 4, 5
- If Int(inputData) = inputData Then
- typeJudge = " BIGINT"
- Else
- typeJudge = " DOUBLE"
- End If
- Case Else
- typeJudge = " VARCHAR(100)"
- End Select
- End Function
复制代码
|
评分
-
2
查看全部评分
-
|