Trimmining a column with bad data

人走茶凉 提交于 2019-11-30 09:32:36

问题


My data looks like

ID    LPNumber 
1     30;#TEST123
2     302;#TEST1232

How can I update MyText to drop everything before the # and including the #, so I'm left with the following:

ID    LPNumber 
1     TEST123
2     TEST1232

I've looked at SQL Server Replace, but can't think of a viable way of checking for the ";"


回答1:


Use CHARINDEX(), LEN() and RIGHT() instead.

RIGHT(LPNumber, LEN(LPNumber) - CHARINDEX('#', LPNumber, 0))



回答2:


On the MSDN REPLACE page, the menu on the left gives the complete list of string functions available.

UPDATE
   MyTable
SET
   LPNumber = SUBSTRING(LPNumber, CHARINDEX('#', LPNumber)+1, 8000);

I'll let you work out (from MSDN) the filter needed in case there is no # in the column...

Edit:

Why 8000?

The longest non-LOB string length is 8000 so it is shorthand for "until end of string". You can use 2147483647 too for max columns or to make it consistent.

Also, LEN can bollix you.

  • SET ANSI_PADDING is ON by default
  • LEN ignores trailing spaces

You'd need to use DATALENGTH but then you need to know the data type because this counts bytes, not characters. See https://stackoverflow.com/a/2557843/27535 for example

So using a magic number is perhaps a lesser evil...



来源:https://stackoverflow.com/questions/8615048/trimmining-a-column-with-bad-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!