使用子查询的查询表达式中的语法错误

时间:2015-05-03 20:52:19

标签: sql sql-server-2008

System.Data.OleDb.OleDbException (0x80040E14) Syntax error in query
expression '(SELECT Sum(tbl_allTransactions.transAmount) AS
SumOftransAmount FROM tbl_allTransactions WHERE
(((tbl_allTransactions.[transType])='Expense')) OR
(((tbl_allTransactions.[transType])='Budget') AND
((tbl_allTransactions.[transMonth])=[@transMonth])) GROUP '. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResulthr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Obje

我收到以下错误: -

String

1 个答案:

答案 0 :(得分:0)

原始代码在第一个子查询上缺少右括号。通过将transType条件从2个语句合并到1,也简化了代码。删除了额外的括号以增强可读性。此外,还将列别名添加到每个子查询的输出中。由于两个查询都呈现相同的数据,因此第二列称为“SumOftransAmount2”

SELECT
(SELECT Sum(tbl_allTransactions.transAmount)
FROM tbl_allTransactions
WHERE tbl_allTransactions.transType in ('Expense', 'Budget') AND tbl_allTransactions.transMonth = @transMonth
GROUP BY tbl_allTransactions.transMonth) as SumOftransAmount
,
(SELECT Sum(tbl_allTransactions.transAmount)
FROM tbl_allTransactions
WHERE tbl_allTransactions.transType in ('Expense', 'Budget') AND tbl_allTransactions.transMonth = @transMonth
GROUP BY tbl_allTransactions.transMonth) as SumOftransAmount2
FROM tbl_allTransactions
WHERE tbl_allTransactions.userID=@userID