You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用.NET C#通过SparkSQL ODBC连接Databricks时临时视图查询报错

问题原因

Simba Spark ODBC驱动默认不允许在单个请求中执行多条SQL语句,而Databricks Notebook会自动拆分多语句独立执行,这就是Notebook中正常但C#代码报错的核心原因。报错信息里的"extra input 'SELECT'",正是因为驱动将两条SQL当成单条语句解析,认为第二个SELECT属于多余的语法输入。

解决方案

提供三种可行方案,按需选择:

方案1:拆分SQL为两次独立执行

在C#代码中,先单独执行创建临时视图的SQL,再执行查询语句,示例代码如下:

using System.Data.Odbc;

var connectionString = "Driver={Simba Spark ODBC Driver};Server=xxxxxxxxx;..."; // 补全你的完整连接串
using var conn = new OdbcConnection(connectionString);
conn.Open();

// 第一步:执行创建临时视图的语句
var createViewSql = @"CREATE OR REPLACE TEMP VIEW budget AS
SELECT 1 as ID, 2025 as OPYEAR, 1 as OPMONTH, 13.2 as BGQTY
UNION ALL
SELECT 2, 2025, 2, 97.1
UNION ALL
SELECT 3, 2025, 3, 105.8;";
using var createCmd = new OdbcCommand(createViewSql, conn);
createCmd.ExecuteNonQuery();

// 第二步:执行查询语句
var querySql = @"SELECT
    SUM(if(date_format(purchdate, ""yyyyMMdd"")='20250313',budget.BGQTY,0)) as daySum
FROM
    CoreData
JOIN budget on budget.OPYEAR= cast(date_format(purchdate, ""yyyy"") as int) 
          and budget.OPMONTH= cast(date_format(purchdate, ""MM"") as int) 
WHERE
         location = 'HDQ';";
using var queryCmd = new OdbcCommand(querySql, conn);
using var reader = queryCmd.ExecuteReader();
// 处理查询结果
while (reader.Read())
{
    Console.WriteLine(reader["daySum"]);
}

方案2:合并为单条SQL语句(用子查询替代临时视图)

将临时视图的逻辑直接嵌入查询的JOIN子句中,避免多语句执行,修改后的SQL如下:

SELECT
    SUM(if(date_format(purchdate, "yyyyMMdd")='20250313',budget.BGQTY,0)) as daySum
FROM
    CoreData
JOIN (
    SELECT 1 as ID, 2025 as OPYEAR, 1 as OPMONTH, 13.2 as BGQTY
    UNION ALL
    SELECT 2, 2025, 2, 97.1
    UNION ALL
    SELECT 3, 2025, 3, 105.8
) as budget on budget.OPYEAR= cast(date_format(purchdate, "yyyy") as int) 
          and budget.OPMONTH= cast(date_format(purchdate, "MM") as int) 
WHERE
         location = 'HDQ';

修改后直接在C#代码中执行这单条SQL即可。

方案3:启用ODBC驱动的多语句支持(谨慎使用)

部分版本的Simba Spark ODBC驱动支持通过连接串参数开启多语句执行,在连接串中添加MULTI_STATEMENTS=1:

Driver={Simba Spark ODBC Driver};Server=xxxxxxxxx;MULTI_STATEMENTS=1;...

注意:该参数并非所有驱动版本都支持,且多语句执行存在SQL注入风险,生产环境需谨慎使用。

内容的提问来源于stack exchange,提问作者sinDizzy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:55:58