在Excel中生成SQL语句的技巧

您是否有任何技巧在Excel中为各种数据导入场景生成SQL语句(主要是INSERT)?

我真的厌倦了用像写公式

="INSERT INTO Table (ID, Name) VALUES (" & C2 & ", '" & D2 & "')"

分号需要在最后一个双引号内加上一个结束符。 在string周围添加单引号时,请记住将其添加到所选单元格的外部。

(为可视性添加的空格 – 在插入之前删除)

=CONCATENATE("insert into table (id, name) values (",C2,",' ",D2," ');")

这是另一种观点:

=CONCATENATE("insert into table (id, date, price) values (",C3,",'",D3,"',",B3,");")

有时我用replace来replaceSQL命令中的模式,而不是试图从串联中构buildsql命令。 假设数据在列A和B中。插入顶行。 在单元格C1中使用模式放置SQL命令:

 insert into table t1 values('<<A>>', '<<B>>') 

然后在第2行放置excel公式:

 =SUBSTITUTE(SUBSTITUTE($C$1, "<<A>>", A2), "<<B>>", B2) 

注意使用绝对单元寻址$C$1来获取模式。 当使用char或varchar并且不得不在拼接中混合使用单引号和双引号时尤其好。 相比于:

 =concatenate("insert into table t1 values '", A2, "', '", B2, "')" 

另外一个不止一次地咬了我的东西就是试图用excel来处理一些数字的字符或者variables,除了它们有前导零(例如007).Excel将会转换为数字7。

我曾经使用String concatenation方法在Excel中创buildSQL插入。 它可以很好地工作,但也可能有点费时和“费力”。

我创build了一个Excel加载项,使得从Excel生成插入更容易:

(请参阅页面底部的video) http://www.howinexcel.com/2009/06/generating-sql-insert-statements-in-excel.html

http://www.querycell.com/SQLGenerator.html

http://www.oneclickcommissions.com/excel-statement.html

VBA的方法是:声明你的string,并像这样分配你的SQL语句

 dim SqlString as String SqlString = "SELECT * FROM %1 WHERE (var=%2)" SqlString = Replace("%1", "Table_Name") SqlString = Replace("%2", ""value"") 

Excel的方法是类似的,但使用SUBSTITUTEfunction。

我更喜欢这种方法,因为它使得SQL文本易读,并避免了所有令人讨厌的连接问题。 是的,它需要一个额外的单元,但它的审计线索是值得的。

我知道这种痛苦。 我最终在我的博客上写了 两遍 。
我创build了一个UDF,它将一系列单元格与几个选项连接起来。 这将始终逗号分隔值,但也可以根据需要添加单引号和/或括号。

所以,你写了sql语句的简单部分。

 INSERT INTO table VALUES /*string that we don't want to type by hand*/ 

要么

 SELECT * FROM table WHERE foo IN (/*another string I don't want to type out*/) 

下面的自定义excel函数会将电子表格范围中的值转换为一个漂亮的string。

 Function SQLConcat(rng As Range, Optional quoted As Boolean = False, Optional parenthesis As Boolean = False) As String ' *************************************************************** ' * Returns a comma separated list for use in SQL IN statements * ' * Params * ' * - rng: Range of cells to concatenate * ' * - quoted: True/False. If true, values are placed inside * ' * of single quotes. Default of false * ' * - parenthesis: Boolean. * ' * Useful for INSERT INTO tbl VALUES(53),(90),(397) * ' * * ' * Author: Christopher J. McClellan * ' * Published under Creative Commons Attribution-Share Alike * ' * http://creativecommons.org/licenses/by-sa/3.0/ * ' * You are free to change, distribute, and pretty much do * ' * whatever you like with the code, but you must give credit * ' * to the original author and publish any derivitive of this * ' * code under the same license. * ' *************************************************************** Dim tmp As String 'temporary string Dim row As Long 'first cell is special case row = 0 'initalize row count Dim c As Object 'cell Dim txtwrapperLeft As String, txtwrapperRight As String If quoted = True And parenthesis = False Then txtwrapperLeft = "'" txtwrapperRight = "'" ElseIf quoted = True And parenthesis = True Then txtwrapperLeft = "('" txtwrapperRight = "')" ElseIf quoted = False And parenthesis = True Then txtwrapperLeft = "(" txtwrapperRight = ")" Else 'quoted = false and parenthesis = false txtwrapperLeft = "" txtwrapperRight = "" End If For Each c In rng.Cells If row = 0 Then tmp = txtwrapperLeft & c.Value & txtwrapperRight Else tmp = tmp & "," & txtwrapperLeft & c.Value & txtwrapperRight End If row = row + 1 Debug.Print tmp Next c 'return SQLConcat = tmp End Function 

为什么你在Excel中生成SQL? 将工作表导出为CSV文件更简单快捷,然后使用一些工具将该文件导入SQL数据库。 例如MySQL的LOAD DATA INFILE语句。

不要直接回答你的问题,我知道这不是所有情况下的解决scheme。

我昨天是这样做的,是的,这是讨厌正确的报价。 我做的一件事是有一个命名的单元格,只包含一个单引号。 inputA1 ="'" (等于,双引号,单引号,双引号),然后通过在最低工具栏左边的框中键入该单元格来命名该单元格为“QUOTE”。

有时候,构buildSQL插入这似乎是最简单的方法。 但是你对此感到厌倦,我不认为有这样的“聪明”的方法(除了macros或者VBA编程之外)。

我会指出你要避免使用Excel,并探索一些其他的想法:

  • 使用Access(伟大的CSV导入filter,然后链接到数据库表,并让Access处理插入)
  • 使用TOAD(甚至更好的导入function,因为它允许您混合和匹配列,甚至从剪贴板导入)
  • 使用SQL Loader(有点棘手的使用,但快速,非常灵活)。

将excel文件导出为csv可能是另一种select(请参阅Bill Krawin的文章 – 作为新的海报,我现在还不能添加评论)。 不过要注意的是,您可能需要将date字段的格式更改为yyyy-mm-dd,否则date列将全部显示00/00/00 – 这是因为MySQL对Microsoft Excel使用了不同的date格式。 或者使用OpenOffice保存csv文件。

如何查询和使用ACE / Jet(aka Access)SQL将数据从Excel工作簿插入到源代码? 这需要一个ACE / Jet可能是另一个Excel电子表格。 这里有一个简单的例子:

 INSERT INTO [ODBC;Driver={SQL Server};SERVER=MYSERVER;DATABASE=MyDatabase;UID=sa;Pwd=mypassword;].MyTable (ID, Name) SELECT F1, F2 FROM [Excel 8.0;HDR=NO;IMEX=1;Database=C:\db.xls;].[Sheet1$A1:B4]; 
Interesting Posts