如何通过修剪最后 8 个字符来返回字符串中的前几个字符?(SQL Server 2008)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9891912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 15:02:53  来源:igfitidea点击:

How to return first few characters in a string by trimming last 8? (SQL Server 2008)

sqlsql-serverstringsql-server-2008

提问by eek

I have a bunch of strings like this:

我有一堆这样的字符串:

 'ABCD99991000'
 'XYZ79991000'
 'E2493991039'

What I really care about is everything before the last 8 characters. The problem is that the characters I care about at the start of the string are of variable length. In the above examples, what I'd want to return is:

我真正关心的是最后8个字符之前的所有内容。问题是我在字符串开头关心的字符是可变长度的。在上面的例子中,我想要返回的是:

 'ABCD'
 'XYZ'
 'E24'

The RIGHT() function would be perfect if I could get it to return everything BEFORE the results. For example, RIGHT(E2499991039,8) returns the numbers I don't want! How can I return the variable length strength before the last 8 characters in my query?

如果我可以让它在结果之前返回所有内容,则 RIGHT() 函数将是完美的。例如,RIGHT(E2499991039,8) 返回我不想要的数字!如何在查询中的最后 8 个字符之前返回可变长度强度?

SQL Server 2008

SQL Server 2008

回答by Irfy

See SUBSTRING

SUBSTRING

select substring(column_name, 1, len(column_name)-8)
from table_name

回答by Mitch Wheat

declare @str varchar(50)

set @str = 'ABCD99991000'

select LEFT(@str, len(@str) - 8)

(No error checking for Len(@str) < 8)

(不对 Len(@str) < 8 进行错误检查)

so,

所以,

select LEFT(colname, LEN(colname) - 8) 
from table_name 

回答by em3ricasforsale

Left(column, length(column - 8))

回答by Louis Ricci

BEGIN
declare @s varchar(16)
select @s = 'abcdefghij'
--
SELECT LEFT(@s, LEN(@s) - 8)
END

回答by Adam

LEFT(E2499991039,LEN(E2499991039)-8)