T-SQL 大写字母前的空格
这个问题是不言自明的。您能指出一种在字符串的每个大写字母之间放置空格的方法吗?
SELECT dbo.SpaceBeforeCap('ThisIsATestString')
会导致
This Is A Test String.
The question is self explanatory. Could you please point out a way to put spaces between each capital letter of a string.
SELECT dbo.SpaceBeforeCap('ThisIsATestString')
would result in
This Is A Test String.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
仅当前一个和下一个字符为小写时才会添加空格。这样,“MyABCAnalysis”将成为“我的 ABC 分析”。
我也添加了对先前空间的检查。由于我们的一些字符串以 'GR_' 为前缀,有些还包含下划线,因此我们可以使用替换函数,如下所示:
select dbo.GR_SpaceBeforeCap(replace('GR_ABCAnalysis_Test','_',' '))
返回“GR ABC 分析测试”
This will add spaces only if the previous and next character is lowercase. That way 'MyABCAnalysis' will be 'My ABC Analysis'.
I added a check for a previous space too. Since some of our strings are prefixed with 'GR_' and some also contain underscores, we can use the replace function as follows:
select dbo.GR_SpaceBeforeCap(replace('GR_ABCAnalysis_Test','_',' '))
Returns 'GR ABC Analysis Test'
假设 SQL Server 2005 或更高版本,此修改自此处的代码: http ://www.kodyaz.com/articles/case-sensitive-sql-split-function.aspx
然后可以按照您上面的建议进行调用。
Assuming SQL Server 2005 or later, this modified from code taken here: http://www.kodyaz.com/articles/case-sensitive-sql-split-function.aspx
This can then be called just as you have suggested above.
该函数结合了之前的答案。有选择地选择保留相邻的 CAPS:
This function combines previous answers. Selectively choose to preserve adjacent CAPS:
为了完全避免循环,使用计数表可以有所帮助。如果您在 SQL 2022 上运行,则
generate_series
函数甚至可以删除此依赖项。此方法将比循环迭代快得多。标量函数不可内联,因此如果您需要的话,我提供了替代的内联表值函数。
To avoid loops altogether, use of a tally table can help here. If you are running on SQL 2022, then the
generate_series
function can remove even this dependency. This method will be significantly faster than iterating through a loop.The scalar function is not inlineable, so I've provided an alternative inline table-valued function if that's what you need.
CLR 和正则表达式或 26 个替换语句、区分大小写的整理子句和修剪。
CLR and regular expressions or 26 replace statements a case sensitive collate clause and a trim.
另一种策略是检查每个字符的 ascii 值:
Another strategy would be to check the ascii value of each character:
虽然我真的很喜欢字符循环的答案,但我对性能并不感到兴奋。我发现对于我的用例来说,这只需一小部分时间即可完成。
这利用了以下事实:
区分大小写的模式搜索仅适用于某些情况排序规则。字符类
[^ ]
表示除空格之外的任何内容,因此当我们将缺失的空格添加到字符串中时,我们会进一步匹配该字符串,直到它完整为止。While I really like the char looping answers I was not thrilled with the performance. I have found this performs in a fraction of the time for my use case.
This makes use of the fact that
case sensitive pattern search only works in some collations. The character class
[^ ]
means anything except space, so as we add the missing spaces we match farther into the string until it is complete.