无忧启动论坛

 找回密码
 注册
搜索

vba将Excel当前活动工作表内容一键生成能够插入到oracle数据库的sql语句

查看数: 1678 | 评论数: 18 | 收藏 0
关灯 | 提示:支持键盘翻页<-左 右->
    组图打开中,请稍候......
发布时间: 2025-4-11 08:16

正文摘要:

本帖最后由 likeyouli 于 2025-8-31 18:07 编辑 内容为原创,ai生成的会有很多小毛病,且很多没有用数组,生成的内容直接粘贴到sql文件里,在sqlplus里执行即可。 Sub 将活动表格内容生成为oracle制表sql语句 ...

回复

a583091790 发表于 3 天前
感谢 楼主,很喜欢VBA
likeyouli 发表于 2025-9-1 16:35:17
楼上回复的这么快啊,,
我先占楼备用







jjhtya 发表于 2025-9-1 16:34:25
谢谢分享
likeyouli 发表于 2025-9-1 16:33:36
本帖最后由 likeyouli 于 2025-9-1 17:53 编辑

直接生成sql文件,且为utf-8编码,速度比用数组快多了,生成后又用vba调用powershell每隔500行插入一行“commit” ,实在费死劲了。最后插入commit的时候可能提示什么错误,但不影响导入。
Sub 生成sql文件且为utf-8编码()
Dim i
filepath1 = "C:\shengcheng.sql"
TableName = InputBox("请输入Oracle表名:", "表名输入", "YOUR_TABLE_NAME")
If Not TableName Like "[a-zA-Z]*" Then MsgBox "表名不是以字母开头,请从新开始": Exit Sub
'因为后边用公式生成的insert into语句最多只能到26个字母,再多只能手动。
For i = 1 To 26
      If Cells(1, i + 1) = "" Then colTypes = colTypes & Cells(1, i) & " varchar2(800)": Exit For
    colTypes = colTypes & Cells(1, i) & " varchar2(800)," & vbCrLf
Next i
strText = "set echo on;" & vbCrLf & "CREATE TABLE " & TableName & vbCrLf & "(" & colTypes & ");" & vbCrLf & "commit;" & vbCrLf
'With New DataObject
'        .SetText strText
'        .PutInClipboard
'    End With
'psCommand = "powershell -Command ""Get-Clipboard -TextFormatType UnicodeText | Out-File -Encoding UTF8 '" & filepath1 & "'"""
'Shell psCommand, vbHide
'Application.Wait Now + TimeValue("00:00:03")
   Dim oShell As Object, psCommand As String
    Set oShell = CreateObject("WScript.Shell")
    psCommand = "powershell -Command " & _
                """$bytes = [System.Text.Encoding]::UTF8.GetBytes('" & strText & "'); " & _
                "$stream = [System.IO.File]::Create('" & filepath1 & "'); " & "$stream.Write($bytes, 0, $bytes.Length); " & "$stream.Close()"""
    oShell.Run psCommand, 1, True
    Set oShell = Nothing

letters = "abcdefghijklmnopqrstuvwxyz"
For i = 1 To 26
      If Cells(1, i + 1) = "" Then xx = xx & """'""" & "&" & Mid(letters, i, 1) & 2 & "&" & """');""": Exit For
     If i = 1 Then
      xx = xx & """INSERT INTO """ & " &" & """" & TableName & """" & "&" & """ VALUES(""" & "&" & """'""" & "&" & Mid(letters, i, 1) & 2 & "&" & """'""" & "&" & """,""" & "&"   '生成的单元格内容被双引号包裹,费劲千辛万苦测试出来
       Else
       xx = xx & """'""" & "&" & Mid(letters, i, 1) & 2 & "&" & """'""" & "&" & """,""" & "&"
      End If
Next i
Cells(2, i + 1) = "=" & xx
h = 10
'h = Range("a1").CurrentRegion.Rows.Count
Cells(2, i + 1).AutoFill Range(Cells(2, i + 1), Cells(h, i + 1))
Range(Cells(2, i + 1), Cells(h, i + 1)).Copy

Set oShell = CreateObject("WScript.Shell")
'psCommand = "powershell -Command ""Get-Clipboard -TextFormatType UnicodeText | Out-File -Encoding UTF8 '" & filepath1 & "'"""
psCommand = "powershell -Command ""Get-Clipboard -TextFormatType UnicodeText | Out-File -Encoding UTF8 -Append '" & filepath1 & "'"""
oShell.Run psCommand, vbNormalFocus, True
'shell psCommand, vbNormalFocus
'Application.Wait Now + TimeValue("00:00:03")
Set oShell = Nothing

   Set oShell = CreateObject("WScript.Shell")
psCommand = "powershell -ExecutionPolicy Bypass -Command " & "Add-Type -AssemblyName System.Text; " & "$i = 0; " & _
                "$sb = [System.Text.StringBuilder]::new(); " & _
                "Get-Content 'c:\shengcheng.sql' -Encoding UTF8 | ForEach-Object { " & _
                "    [void]$sb.AppendLine($_); " & _
                "    $i++; " & "    if ($i % 500 -eq 0) { [void]$sb.AppendLine('commit;') } " & "}; " & _
                "[void]$sb.AppendLine('commit;'); " & _
                "$bytes = [System.Text.Encoding]::UTF8.GetBytes($sb.ToString()); " & _
                "$stream = [System.IO.File]::Create('c:\output.sql'); " & _
                "$stream.Write($bytes, 0, $bytes.Length); " & _
                "$stream.Close()"
   ' Set shell = CreateObject("WScript.Shell")
    oShell.Run psCommand, vbNormalFocus, True
    Set oShell = Nothing
MsgBox "文件已生成到: " & filePath & "和" & filepath1 & "且添加为commit后为c:\output.sql"
End Sub









likeyouli 发表于 2025-8-28 16:03:34
在行: 1 上开始执行命令时出错 -
INSERT INTO NIHAO VALUES
('11413053010003679771','37083019990129394X','胡秋英','居民','H37083000077','东和县人民医院','2518363-001','','BI63900','住院诊查费','22','1','22','2025-07-01','22','0','0','0','110200005','住院诊查费','','','0','0','', ''),
('11413053010003679771','37083019990129394X','胡秋英','居民','H37083000077','东和县人民医院','2518363-001','','BI63900','三人间(一等)','45','1','45','2025-07-01','35','0','10','0','110900001b1','三人间(一等)','','','0','10','', ''),
('14370830193701125000','370830199901125711','薛芳茂','职工','H37083000077','东和县人民医院','*37000000002115473456','帕金森综合征','M02301','卡左双多巴缓释片','1.655667','120','198.68','2025-07-06','0','178.81','0','19.87','XN04BAK135A010010104495','卡左双多巴缓释片','卡比多巴50mg,左旋多巴200mg','卡左双多巴缓释片','0','0','e7', '')
错误位于命令行: 3 列: 43
错误报告 -
SQL 错误: ORA-00933: SQL 命令未正确结束

https://docs.oracle.com/error-help/db/ora-00933/00933. 00000 -  "unexpected keyword at or near %s"
*Cause:    An unexpected keyword was encountered in the SQL statement at
           or near the position printed in the error message.
           One of the following occurred:
           1. You had a typo in your SQL statement.
           2. Unsupported syntax was encountered for a clause in the
           statement.
           3. An unsupported clause was encountered in the statement.
           4. A string was terminated prematurely leading to the rest
           of the string to be interpreted as keywords. For example, an
           apostrophe in the string may be causing it to
           end prematurely.
*Action:   Take the action that corresponds with the Cause
           1. Check that your SQL statement has no typos.
           2. Check Oracle Database documentation to find the
           correct syntax for the clause and update the problematic
           clause appropriately.
           3. Check Oracle Database documentation to find the correct
           syntax for the statement and remove the unsupported clause.
           4. Enter two single quotes instead of one to represent an
           apostrophe within a string.
*Params:   1) keyword_value
           keyword near the keyword causing the error. The keyword value
           may be truncated for readability if it is too long.
这个错误 ORA-00933: SQL 命令未正确结束 的原因是:Oracle 数据库不支持在一条 INSERT 语句中使用多个 VALUES 子句进行多行插入。

你的语法是其他数据库(如 MySQL、PostgreSQL、SQL Server)支持的多行插入语法,但 Oracle 不支持这种写法。
https://chat.deepseek.com/a/chat ... a-b56c-8ad0e5334e8b
likeyouli 发表于 2025-8-28 14:52:02
"'"&A2&"',"&"'"&B2&"',"&"'"&C2&"',"&"'"&D2&"',"&"'"&E2&"',"&"'"&F2&"',"&"'"&G2&"',"&"'"&H2&"',"&"'"&I2&"',"&"'"&J2&"',"&"'"&K2&"',"&"'"&L2&"',"&"'"&M2&"',"&"'"&N2&"',"&"'"&O2&"',"&"'"&P2&"',"&"'"&Q2&"',"&"'"&R2&"',"&"'"&S2&"',"&"'"&T2&"',"&"'"&U2&"',"&"'"&V2&"',"&"'"&W2&"',"&"'"&X2&"',"&"'"&Y2&"',"&" '"&Z2&"'"       ----------------------------------------------------------------------
"INSERT INTO nihao VALUES("&AA2&");"

aduge38 发表于 2025-8-28 11:37:00
不明觉厉啊,谢谢分享
sjp060305 发表于 2025-8-28 11:25:19
虽然不知道LZ在说什么但是感觉很厉害的样子~
likeyouli 发表于 2025-8-28 11:24:46
本帖最后由 likeyouli 于 2025-8-28 13:40 编辑

Sub 将活动表格标题生成sqlserver建表语句()
'需要确保在VBA编辑器中已引用"Microsoft Forms 2.0 Object Library"(通常在引用列表中显示为"FM20.dll")
    Dim strText As String, colTypes As String, values As String
  '首先生成create表语句,默认首行为标题
arr = Range("a1").CurrentRegion
TableName = InputBox("请输入Oracle表名:", "表名输入", "YOUR_TABLE_NAME")
'If Not TableName Like "[a-zA-Z]*" Then MsgBox "表名不是以字母开头,请从新开始": Exit Sub
For i = 1 To UBound(arr, 2)
If Len(Trim(arr(1, i))) = 0 Then MsgBox "第一行有空单元格": Exit Sub
Next i
For i = 1 To UBound(arr, 2)
    colnames = colnames & arr(1, i)
    If i < UBound(arr, 2) Then colnames = colnames & ","
    colTypes = colTypes & arr(1, i) & " varchar(800)," & Chr(13)
Next i
   colTypes = Left(colTypes, InStrRev(colTypes, ",") - 1) & Mid(colTypes, InStrRev(colTypes, ",") + 1)
'以上为生产建表语句
strText = "CREATE TABLE  " & "[dbo].[" & TableName & _
"](" & Chr(13) & colTypes & ") ON [PRIMARY]"

    ' 将文本放入剪贴板
    With New DataObject
        .SetText strText
        .PutInClipboard
    End With
    MsgBox "生成的sql语句已复制到粘贴板!"
End Sub
classMain 发表于 2025-4-11 17:42:47
感谢分享
wang1126 发表于 2025-4-11 16:55:07
谢谢楼主分享
yzszh64 发表于 2025-4-11 16:26:06
感谢分享,
wwss707 发表于 2025-4-11 14:31:44

谢谢分享!
hmaaaa 发表于 2025-4-11 14:12:18
THX~!感恩分享摟,謝謝大大喔~~!辛苦了!^^
guong 发表于 2025-4-11 12:58:38
谢谢分享
wn168cn@163.com 发表于 2025-4-11 09:34:21
感谢分享
yc2428 发表于 2025-4-11 09:24:25
谢谢分享!
小灰兔 发表于 2025-4-11 08:43:50
感谢分享

小黑屋|手机版|Archiver|捐助支持|无忧启动 ( 闽ICP备05002490号-1 )

闽公网安备 35020302032614号

GMT+8, 2025-9-13 07:31

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表