[英]SQL Server Using a condition in a Substring
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. 我想选择连字符右边的所有内容然后如果该子字符串的长度> 2我想要更新该字段并将其设置为自己减去右边的两个额外数字。
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 . 我真正想要做的是创建一个更新语句,如果有超过2个字符,则测试连字符右侧的字符,然后截断任何多余的字符。
Any suggestions would be appreciated. 任何建议,将不胜感激。 Thanks 谢谢
Try this: 试试这个:
Select SUBSTRING(Account,0,CHARINDEX('-',Account)+3) as UpdatedAccount, Account
FROM Documents
WHERE SubmissionID=45925
and LEN(SUBSTRING(Account, CHARINDEX('-',Account)+1,LEN(Account)) ) > 2
AND CHARINDEX('-',Account) > 0
It's ugly but appears do do what you want 这很丑,但似乎做你想做的事
Your update would look like this: 您的更新将如下所示:
UPDATE Documents
SET Account = SUBSTRING(Account,0,CHARINDEX('-',Account)+3)
WHERE SubmissionID=45925
and LEN(SUBSTRING(Account, CHARINDEX('-',Account)+1,LEN(Account)) ) > 2
AND CHARINDEX('-',Account) > 0
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. 也就是说,我建议使用@Richards解决方案。 It's much prettier. 它更漂亮。
You could use a Common Table Expression if you are using SQL Server 2005 or greater. 如果您使用的是SQL Server 2005或更高版本,则可以使用公用表表达式 。
WITH CTE
AS
(
SELECT Account
, CHARINDEX('-', Account) AS [Dash Index]
, CASE
WHEN CHARINDEX('-', Account)+2 > 2
THEN CHARINDEX('-', Account)+2
ELSE LEN(Account)
END AS [Acceptable Length]
, LEN(Account) AS [Total Length]
FROM Documents
)
UPDATE CTE
SET Account = SUBSTRING(Account, 1, [Acceptable Length])
WHERE [Total Length] <> [Acceptable Length]
UPDATE Documents
SET Account = STUFF(Account, CharIndex('-', Account)+3, 1000, '')
where SubmissionID=45925 AND Account like '%-___%'
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. 这里是。
Update Documents
Set Acount=LEFT(Account,Len(Account)-2)
WHERE Submid=41632 AND Account LIKE '%-____'
(Thanks to @Richard for that last bit!') (感谢@Richard最后一点!')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.