SQL Server 在子字符串中使用条件
我有一个由这样的帐号组成的数据字段,
16530907-00
16530907-0001
16589553-00
16589553-00
我想选择连字符右侧的所有内容,然后如果该子字符串的长度大于 2,我想更新该字段并将其设置为自身减去两个额外的值右边的数字。
我正在练习 select 语句
Select SUBSTRING(Account, CHARINDEX('-'), Account)+1, LEN(Account) as test
FROM Documents
WHERE SubmissionID=45925 and LEN(test)>2
这不起作用。我真正想做的是创建一个更新语句,测试连字符右侧的字符是否超过 2 个字符,然后截断任何多余的字符。
任何建议将不胜感激。 谢谢
I have a field of data which consists of account numbers like this
16530907-00
16530907-0001
16589553-00
16589553-00
I want to select everything to the right of the hyphen then if the Length of that substring is >2 I want to Update that field and set it to itself minus the two extra digits on the right.
I am practicing with a select statement
Select SUBSTRING(Account, CHARINDEX('-'), Account)+1, LEN(Account) as test
FROM Documents
WHERE SubmissionID=45925 and LEN(test)>2
This does not work. What I really want to do is create an update statement that tests the characters to the right of the hyphen if there are more than 2 characters then truncate any extra characters .
Any suggestions would be appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
试试这个:
它很丑陋,但似乎做你想做的事
你的更新看起来像这样:
更新:
添加了对没有连字符场景的检查,这样你就不会无缘无故地取消日期。也就是说,我建议使用@Richards 解决方案。它漂亮得多。
Try this:
It's ugly but appears do do what you want
Your update would look like this:
UPDATE:
Added in a check for no hyphen scenarios so you don't undate for no reason. That said, I would recommend going with @Richards solution. It's much prettier.
您可以使用公用表表达式如果您使用的是 SQL Server 2005 或更高版本。
You could use a Common Table Expression if you are using SQL Server 2005 or greater.
感谢大家的意见和建议。我使用了这里的一些内容来设计一个我认为对我来说很有效的解决方案。这里是。
(感谢@Richard 的最后一点!')
Thanks to everyone for their comments and suggestions. I used some of what was here to devise a solution that I think will work well for me. Here it is.
(Thanks to @Richard for that last bit!')