获取varchar SQL左侧的第一个空格

时间:2012-01-11 10:23:31

标签: sql varchar

我有一个Nvarchar列,其中包含'John Smith'

我想把它分成'John Smith'和''

知道怎么做吗?我尝试了长度,但没有考虑左侧空格

4 个答案:

答案 0 :(得分:3)

对于nvarchar:

,此函数返回字符串长度的2倍,包括空格
DATALENGTH(@variable)

因此LEFT(@variable, LEN(@variable))RIGHT(@variable, DATALENGTH(@variable) / 2 - LEN(@variable))应该有效。

我假设您使用nvarchar这是SQL Server ...

答案 1 :(得分:1)

在查询中,请尝试:

...
rtrim(MyColumn) NoTrailingSpaces,
right(MyColumn, len(MyColumn) - len(rtrim(MyColumn)) ) TrailingSpacesOnly,
...

答案 2 :(得分:1)

- 从数据中分离出来。如果您喜欢,请更换PADDING字符

DECLARE @js varchar(50)
DECLARE @M INT
DECLARE @I INT
DECLARE @C CHAR
DECLARE @WORD VARCHAR(50)
DECLARE @LPAD VARCHAR(50)
DECLARE @RPAD VARCHAR(50)
DECLARE @LEFT_PADDING_CHARACTER CHAR
DECLARE @RIGHT_PADDING_CHARACTER CHAR
DECLARE @TERMINATOR_CHARACTER CHAR

-- INIT THE STRINGS
SELECT @LPAD = ''
SELECT @RPAD = ''
SELECT @WORD = ''
SELECT @LEFT_PADDING_CHARACTER = ' '
SELECT @RIGHT_PADDING_CHARACTER = ' '
SELECT @TERMINATOR_CHARACTER = '~'  
SELECT @js = '    John Smith '
SELECT @js = @js + @TERMINATOR_CHARACTER    -- ADD TO CALC THE LENGTH
SELECT @I = 1                               -- FIRST CHARACTER
SELECT @M = LEN(@JS)                        -- LAST CHARACTER

WHILE @I < @M               -- PARSE OUT THE LEFT PADDING
BEGIN
    SELECT @C = SUBSTRING(@js, @I, 1)   
    IF @C = @LEFT_PADDING_CHARACTER SELECT  @LPAD = @LPAD + @C
    ELSE GOTO PARSERIGHTPADDING
    SELECT @I = @I + 1
END

PARSERIGHTPADDING:
SELECT @I = LEN(@JS) -1     -- POINT TO THE LAST CHAR
SELECT @M = 1           -- POINT TO THE FIRST CHAR
SELECT @js = LTRIM(@JS)     -- TRIM OFF THE LEFT PADDING
SELECT @js = REPLACE(@js, @TERMINATOR_CHARACTER, '' -- TRIM OFF THE TERMINATOR

WHILE @M < @I               -- PARSE OUT THE RIGHT PADDING
BEGIN       
    SELECT @C = SUBSTRING(@js, @I, 1)
    IF @C = @RIGHT_PADDING_CHARACTER SELECT  @RPAD = @RPAD + @C
    ELSE GOTO REMOVEPADDINGS
    SELECT @I = @I - 1
END

REMOVEPADDINGS:
SELECT  @WORD = LTRIM(RTRIM(@js))

-- SELECT THE RESULTS TO VIEW THEM @LPAD AND @RPAD SHOULD BE BLANK
SELECT @LPAD [LPAD], @WORD [WORD], @RPAD [RPAD]

答案 3 :(得分:0)

示例:

DECLARE @js NVARCHAR(MAX) = N'John Smith '
SELECT CASE WHEN RIGHT(@js, 1) = NCHAR(32) THEN SUBSTRING(@js, 1, DATALENGTH(@js)/2-1) ELSE @js END JohnSmith,
 CASE WHEN RIGHT(@js, 1) = NCHAR(32) THEN NCHAR(32) ELSE N'' END Space