1

我想我有一个简单的问题。我想遍历 varchar 变量中的字符对并检查一些东西。我尝试使用这个简单的代码(如下所示),但我得到了两次打印的“ho”。为什么第二个 LEFT 不起作用?

declare 
@name nvarchar(50),
@temp nvarchar(50)
set @name = 'house'
set @temp = @name
set @temp = Left(@temp,2)
print @temp
set @temp = Left(@temp,2)
print @temp
4

3 回答 3

1

Taken from MSDN documentation:

Returns the left part of a character string with the specified number of characters.

Therefore Left(@temp,2) will return "ho"

Left("ho",2) will also return "ho".

Therefore you will always get "ho".


If you wish to PRINT the first 2 letters, then remove them, you could do:

PRINT Left(@temp,2)
SET @temp = SUBSTRING(@temp, 2, LEN(@temp)-2)

If you are to then call Left(@temp,2) again, you would get "us"

于 2012-11-26T11:07:24.810 回答
0

This is working exactly as it should be:

declare 
@name nvarchar(50),
@temp nvarchar(50)
set @name = 'house'
set @temp = @name
set @temp = Left(@temp,2) --here @temp has ho
print @temp
set @temp = Left(@temp,2) -- you are trying again to get 
                          --left ('ho',2)
                          --this will again return you ho
print @temp

At first set @temp = Left(@temp,2), you are setting temp to hold 'ho'. In the second set statement you are again trying to access 2 characters from the left on string 'ho' this will again give you the same thing.

于 2012-11-26T11:06:30.843 回答
0

SQL Server 中的 LEFT() 函数将仅打印从字符串左侧指定的字符数。根据您的要求,您需要将 SUBSTRING() 函数与 WHILE 语句一起使用。下面给出一个例子:

declare @str varchar(5)='house'
declare @i int = 1
while @i<len(@str)
begin
print SUBSTRING(@str,@i,2)
set @i=@i+1
end

输出:你看到了吗

于 2017-10-05T12:58:31.080 回答