-1

我的代码中出现以下语句的语法错误,我已经完成了它,除非我错过了什么,否则我看不到任何错误:

错误是

关键字 RIGHT 附近的语法不正确”

("SELECT D1.DR, D1.CR, D1.ASSET_NO, (Coalesce(addit_ytd,0) + DR - CR) AS ADDIT_YTD"
+"FROM (SELECT coalesce (sum(dr_amount),0) AS DR, coalesce (sum(cr_amount),0) AS CR , asset.asset_no" 
+"FROM posting RIGHT JOIN asset ON asset.asset_no = posting.asset_no, sysasset" 
+"WHERE asset.asset_no = @AssetNumber" 
+"AND (period <= posting.period) AND (period >= sysasset.asset_open_per)" 
+ "GROUP BY asset.asset_no) AS D1 INNER JOIN dbo.asset ON D1.asset_no= asset.asset_no", DataAccess.AssetConnection); 
4

4 回答 4

7

正如其他人所说,您缺少空格。考虑重写代码以使用 C# 的逐字字符串语法,并可能在其中添加一些缩进以更好地指示查询的结构:

(@"SELECT D1.DR, D1.CR, D1.ASSET_NO, (Coalesce(addit_ytd,0) + DR - CR) AS ADDIT_YTD
FROM 
    (SELECT coalesce (sum(dr_amount),0) AS DR, coalesce (sum(cr_amount),0) AS CR ,     asset.asset_no
    FROM posting RIGHT JOIN asset ON asset.asset_no = posting.asset_no, sysasset
    WHERE asset.asset_no = @AssetNumber
    AND (period <= posting.period) AND (period >= sysasset.asset_open_per)
    GROUP BY asset.asset_no) 
AS D1 INNER JOIN dbo.asset ON D1.asset_no= asset.asset_no",         
DataAccess.AssetConnection); 

看,@ 符号的意思是“直接从源代码中取出字符串”。源代码中的所有空格都会变成字符串中的空格。

于 2013-04-09T15:04:52.967 回答
2

如果字符串在连接期间出现错误。FROM您需要在列之后或子句之前有额外的空间,

("SELECT D1.DR, D1.CR, D1.ASSET_NO, (Coalesce(addit_ytd,0) + DR - CR) AS ADDIT_YTD" +
" FROM (SELECT coalesce (sum(dr_amount),0) AS DR, coalesce (sum(cr_amount),0) AS CR , asset.asset_no" +
" FROM posting RIGHT JOIN asset ON asset.asset_no = posting.asset_no, sysasset" +
" WHERE asset.asset_no = @AssetNumber" +
" AND (period <= posting.period) AND (period >= sysasset.asset_open_per)" + 
" GROUP BY asset.asset_no) AS D1 INNER JOIN dbo.asset ON D1.asset_no= asset.asset_no", DataAccess.AssetConnection); 
 ^ << for clarity add extra space here

如果你不添加额外的空间,选择语句将被解析为

... (Coalesce(addit_ytd,0) + DR - CR) AS ADDIT_YTDFROM (SELECT coalesce
                                                  ^ causes syntax error
于 2013-04-09T14:27:15.700 回答
1

除了所有其他答案之外,我还要指出,通常当我有任何 SQL 进入生产代码时,我通常将其作为资源包含并以这种方式引用文本,而不是将其硬编码在 c# 代码中. 这使您可以在多个地方重复使用 SQL 代码,并且还可以在您确实需要编辑 SQL 代码时更轻松地阅读它。

于 2013-04-09T16:45:40.170 回答
1

您在每行之间缺少空格字符:

... ADDIT_YTD" +
"FROM ( ...

变成

... ADDIT_YTDFROM ( ...

等等

仅仅因为您的源代码中有换行符,并不意味着这些换行符出现在您构造的文本中。(附带说明一下,在它不是语法正确的 SQL 之前,它走多远(显然到第三行的中间)给我留下了深刻的印象)

于 2013-04-09T14:27:58.220 回答