【问题标题】:Updating SQL SERVER Database from EXCEL从 EXCEL 更新 SQL SERVER 数据库
【发布时间】:2013-12-11 00:43:18
【问题描述】:

我有一个包含一些数据的 Excel 表:

1. Inventory item number 
2. Description
3. Inventory Database ID (PRIMARY KEY)

我有大约 1000 行。我想删除数据库中与我的 excel 列表中的项目编号匹配的项目编号。我可以在 .NET 中编写一个应用程序来执行此操作,但这似乎过于复杂。

有没有一种简单的方法可以通过 excel 或 SQL Server 运行 sql 语句来删除我的 excel 表中的项目编号,而无需创建应用程序?

【问题讨论】:

  • 您是否有权访问 SQL Server Management Studio?

标签: sql-server excel


【解决方案1】:

为了快速更新。我觉得这是最好的方法。

在 Excel 中添加一列并将您的更新语句构造为公式,即:

="DELETE Table1 WHERE ItemNumber='"&A1&"' AND InventoryId = "&C1

将公式复制下来,然后将结果复制/粘贴到 SQL 窗口中并运行它。

专业提示,如果您有很多撇号要处理,那么事先进行全局查找/替换可能是值得的。或者你可以从公式中处理它们。即:

="DELETE Table1 WHERE ItemNumber='"&SUBSTITUTE(A1,"'","''")&"' AND InventoryId = "&C1

【讨论】:

  • 对于撇号,您可以快速更新您的公式="DELETE Table1 WHERE ItemNumber='"&substitute(A1,"'","")&"' AND InventoryId = "&C1
  • 谢谢@nutsch,我更新了我的答案,使其更加彻底。通常全局查找/替换是安全的,因为添加列类型会破坏文件以用于其他目的。
  • 我不确定这是否适合我。我有大约 500 行要删除。可能有 10-20 行,再多的话就太费劲了..
  • 为什么工作量太大? @Malk 给出的公式可以简单地填写、复制、粘贴和执行。还有其他要求吗?
  • 我可以生成一个脚本并通过 ssms 运行吗? like 'code' DELETE FROM TABLE WHERE itemnumber=123 DELETE FROM TABLE WHERE itemnumber=124 DELETE FROM TABLE WHERE itemnumber=125 'code' 并运行每一行?
【解决方案2】:

如果你不想通过 SQL 接口,你可以从 excel 中运行附加的代码,在明显更新连接字符串之后。

Sub ExecuteSQLCommand()
'Execute the SQL string passed through

Dim conn As ADODB.Connection, strConn As String, sSQLCommand As String
Dim cmd As ADODB.Command, lLoop As Long, lLastRow As Long

Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB;" & _
                                "Data Source=DCC08SQL;" & _
                                "Initial Catalog=HarvestPress;" & _
                                "Integrated Security=SSPI;" & _
                                "Database=HarvestPress;" & _
                                "Trusted_Connection=True;"

conn.Open

Set cmd = New ADODB.Command

lLastRow = Cells(Rows.Count, 1).End(xlUp).Row

With cmd
    .ActiveConnection = conn
    .CommandType = adCmdText

    For lLoop = 1 To lLastRow
        sSQLCommand = "DELETE FROM Table1 WHERE ItemNumber='" & Cells(lLoop, 1) & "' AND InventoryId = " & Cells(lLoop, 1)
        .CommandText = sSQLCommand
        .Execute
    Next lLoop

End With

conn.Close
Set conn = Nothing
Set cmd = Nothing

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多