SQL Server 版本的 MySQL 的 group_concat 和转义字符串
我只有 MS SQL Server 2008 和 Visual Studio 的 Express 版本。鉴于我无法创建 SQL Server 项目,因此 CLR 解决方案是不可能的,我尝试使用
select col1, stuff( ( select ' ' + col2
from StrConcat t1
where t2.col1 = t1.col1
for xml path('')
),1,1,'')
from StrConcat t2
group by col1
order by col1
来获取行连接的 col2。 col2 是一个 varchar 字段,带有一些控制字符,例如 & 和 \n。当它与上面的 SQL 连接时,它似乎转义了那些控制字符,即。 & 变为 &放大器;并且 \n 变成 &#xOD,这不是我想要的。考虑到 col1 和串联字段将用于更新另一个表,那么以未转义的原始形式获取串联字段的最佳方法是什么,或者没有,唯一的方法是求助于外部代码?
表架构如下所示: StrConcat(id int 主键,col1 int,txt varchar(80)) col1 有索引,txt 应按 col1 分组,按组内的 id 排序。
I only have the Express versions of MS SQL Server 2008 and Visual Studio. Given that I can't create a SQL Server project and therefore CLR solutions are out of the question, I've attempted to use
select col1, stuff( ( select ' ' + col2
from StrConcat t1
where t2.col1 = t1.col1
for xml path('')
),1,1,'')
from StrConcat t2
group by col1
order by col1
to get a row concatenated col2. col2 is a varchar field with some control characters like & and \n. When it is concatenated with the above SQL, it appears to escape those control characters ie. & becomes
& amp ; and \n becomes OD, which is not what I want it to do. Given that the col1 and concatenated field is going to be used to update another table, what is the best way to get the concatenated field in its unescaped original form or is there none and the only way is to resort to external code?
The table schema looks like this:
StrConcat (id int primary key, col1 int, txt varchar(80))
col1 has an index on it, txt should be grouped by col1, ordered by id within the group.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,这种行为是设计使然。如果不以这种方式转义,查询可能会输出无效的 XML。
如果您需要在 SQL Server 中获取未转义的值,则必须使用 其他串联方法(递归 CTE 通常是继 CLR 聚合和
FOR XML
之后最有效的方法,但最难来写)。当然,如果将其直接传递到应用程序,则在那里取消转义会更容易,即使用 .NET 中的 XmlReader 类。
The behaviour is, of course, by design. If it didn't escape this way, the query could output invalid XML.
If you need to get an unescaped value within SQL Server, then you'll have to use one of the other concatenation methods (recursive CTE is usually the next-most efficient after CLR aggregate and
FOR XML
, but hardest to write).Of course, if this is being passed directly to an application, it will be much easier to unescape it there, i.e. using the XmlReader class in .NET.