2012-11-26 55 views
1

我想我有一個簡單的問題。我想運行一個varchar變量中的字符對並檢查一些內容。我試圖用這個簡單的代碼(如下圖所示) ,但我得到'ho'印兩次。爲什麼不是第二個LEFT的作品?使用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 

回答

0

這是工作,正是因爲它應該是:

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 

起初set @temp = Left(@temp,2),要設置臨時舉行'ho'。在第二組聲明中,您再次嘗試訪問字符串'ho'左側的2個字符,這將再次爲您提供相同的內容。

+0

哦我傻!謝謝 –

+0

@EladFranklin,歡迎您 – Habib

1

MSDN documentation摘自:

返回一個字符串,指定的字符數 的左側部分。

因此Left(@temp,2)將返回 「豪」

Left("ho",2)也將返回 「豪」。

因此,你總是會得到「ho」。


如果你想PRINT的前兩個字母,然後刪除它們,你可以這樣做:

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

如果你是再次打電話Left(@temp,2),你會得到「我們」

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 @[email protected]+1 
end 

輸出: 豪 歐 我們 SE Ë