简体   繁体   English

使用XML路径的Visual Studio 2010和Query Designer SQL问题

[英]Visual Studio 2010 and Query Designer SQL Problem with XML Path

I have an awesome Visual Studio 2010 SQL frustration: 我对Visual Studio 2010 SQL感到很沮丧:

I found code on StackOverflow on how to concatenate strings from multiple rows onto a single row by using FOR XML PATH(''). 我在StackOverflow上找到了有关如何使用FOR XML PATH('')将字符串从多行连接到单行的代码。

When I write the following line in Query and View Designer (because, presumably, there is no other way to write SQL in Visual Studio and then save it as a "View"), I get results that are not what I want: 当我在查询和视图设计器中编写以下行时(因为,大概没有其他方法可以在Visual Studio中编写SQL,然后将其另存为“视图”),我得到的结果不是我想要的:

Code: 码:

Names AS
(SELECT DISTINCT 
  Z.code,
  (SELECT DISTINCT CAST(B.fname + ' ' + B.lname + ' ' AS VARCHAR(MAX))
   FROM Records AS A LEFT OUTER JOIN Employees AS B ON A.id = B.id
   WHERE (A.code = Z.code) FOR XML PATH('')) AS EmployeeNames
 FROM Employees AS Z)

I get a result like: 我得到的结果是:

Code  EmployeeNames
----  -------------------------
1234  <Expr1>First Last</Expr1>

Why? 为什么? Because Visual Studio 2010, in all it's glory, adds "as Expr1" to the following: 因为Visual Studio 2010充满荣耀,所以将“ as Expr1”添加到以下内容:

(SELECT DISTINCT CAST(B.fname + ' ' + B.lname + ' ' AS VARCHAR(MAX))
 FROM Records AS A LEFT OUTER JOIN Employees AS B ON A.id = B.id
 WHERE (A.code = Z.code) FOR XML PATH('')) *as Expr1*

Is there any work-around for this? 有什么解决方法吗? I've noticed that the problem comes with the Query and View Designer Parser... and I can intentionally break the parser by putting a random function that the parser doesn't support (like OVER()) somewhere in my code. 我注意到问题出在查询和视图设计器解析器中……我可以通过在代码中放置一个解析器不支持的随机函数(例如OVER())来故意破坏解析器。 This fixes the problem, and removes the XML tags, but seems unnecessary. 这样可以解决问题,并删除XML标记,但是似乎没有必要。

Does anyone else have this problem? 还有其他人有这个问题吗? Does anyone know a work-around? 有谁知道解决方法?

Thank you very much for your time and effort with my problem. 非常感谢您花费时间和精力解决我的问题。

I ran into something simular and the fix for me was to define the Cast in each case. 我遇到了类似的问题,而对我来说,解决方法是在每种情况下定义Cast。

Example: 例:

Names AS (SELECT DISTINCT Z.code, (SELECT DISTINCT CAST(B.fname AS varchar(10) + ' ' + CAST (B.lname AS varchar(10) + ' ') FROM Records AS A LEFT OUTER JOIN Employees AS B ON A.id = B.id WHERE (A.code = Z.code) FOR XML PATH('')) AS EmployeeNames FROM Employees AS Z) 从记录中向左命名AS(SELECT DISTINCT Z.code,(SELECT DISTINCT CAST(B.fname AS varchar(10) +''+ CAST (B.lname AS varchar(10) +'')) ON A.id = B.id WHERE(A.code = Z.code)FOR XML PATH(''))AS EmployeeNames FROM Employees AS Z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM