问题
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