【问题标题】:Sub-Select query error in SQL Server 2008SQL Server 2008 中的子选择查询错误
【发布时间】:2013-04-03 12:36:06
【问题描述】:

考虑以下查询:

insert into dbo.SubscriptionDetails (taxonomyid) 
values(select objectid from SubscriptionObjects where objectname=?)

此查询在我的本地环境中运行良好,但在执行生产环境时出现问题。

子选择查询是否需要在 SQL-Server 级别设置任何属性?

我使用 Java - JDBC 处理 SQL 事务。

查看下面的堆栈跟踪:

2013.03.28 15:42:11 CDT ERROR Error while inserting records into SubscriptionDetails table..
java.sql.BatchUpdateException: Subqueries are not allowed in this context. Only scalar expressions are allowed.

【问题讨论】:

    标签: java sql-server sql-server-2008 jdbc


    【解决方案1】:

    我很惊讶您的版本适用于任何环境!尽量省略values:

    insert  into dbo.SubscriptionDetails 
            (taxonomyid) 
    select  objectid 
    from    SubscriptionObjects 
    where   objectname=?
    

    对于多个子查询,您可以:

    insert  into dbo.SubscriptionDetails 
            (taxonomyid, contenttypeid) 
    select  (select objectid from SubscriptionObjects where objectname=?)
    ,       (select objectid from SubscriptionObjects where objectname=?)
    

    或者,使用括号通过values 强制标量上下文:

    insert  into dbo.SubscriptionDetails 
            (taxonomyid, contenttypeid) 
    values  ((select objectid from SubscriptionObjects where objectname=?),
             (select objectid from SubscriptionObjects where objectname=?))
    

    【讨论】:

    • 道歉,但它是一个单一的插入查询...选择是插入查询的一部分。
    • @TeeGee:当你运行这个查询时,你是遇到错误还是什么?
    • @Quassnoi - 是的,我愿意,请参阅附加的 StackTrace。我与生产环境中的数据有关。谢谢!
    • 这是我在 Java 中使用的确切的准备好的语句......并且它有效。插入 dbo.SubscriptionDetails (userid,eventid,taxonomyid,contenttypeid,typeid) values(?,?,"+ "(select objectid from SubscriptionObjects where objectname=?),"+ "(select objectid from SubscriptionObjects where objectname=?), " + "?)
    • @Andomar 你能解释一下强制标量上下文是什么意思吗?为什么会出现这个错误?
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多