我的代码中出现了以下语句的语法错误,我已经完成了它,除非我错过了一些内容,否则我看不出任何错误:
错误是
关键字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);
答案 0 :(得分: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);
请参阅,@符号表示“直接从源代码中取出字符串”。源代码中的所有空格都成为字符串中的空格。
答案 1 :(得分: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
如果您不添加额外空间,则会将select语句解析为
... (Coalesce(addit_ytd,0) + DR - CR) AS ADDIT_YTDFROM (SELECT coalesce
^ causes syntax error
答案 2 :(得分:1)
您在每行之间缺少空格字符:
... ADDIT_YTD" +
"FROM ( ...
变为
... ADDIT_YTDFROM ( ...
等
仅仅因为您的来源中有换行符,并不意味着这些换行符会显示在您构建的文本中。 (另一方面,在它不是语法正确的SQL之前,我对它到底有多远(显然是在第3行的中间)留下了深刻的印象。
答案 3 :(得分:1)
除了所有其他答案之外,我还会指出,通常当我有任何进入生产代码的SQL时,我通常会将其作为资源包含在内,而不是在内部硬编码c#代码。这使您可以在多个位置重用SQL代码,并且还可以在需要编辑时更轻松地读取SQL代码。