2013-02-28 80 views
3

我寫了一個查詢(這是查詢的最簡單的形式)怪異的行爲

declare @tbl1 table(name varchar(50)) 
declare @tbl2 table(name varchar(50)) 
declare @query varchar(600) 
set @query = '' 

insert into @tbl1 
select 'a' union select 'b' union select 'c' union select 'd' union select 'e' 

insert into @tbl2 
select '1' union select '2' union select '3' union select '4' union select '5' 

select 
@query = 
' Go ' + 
@query + 
tbl1.name + ' (' + 
substring(
(
    select ', ' + tbl2.name 
    from @tbl2 as tbl2 
    for xml path('') 
), 3, 5000) + ') ' 
from @tbl1 as tbl1 

print @query 

我期待一個結果,這樣

GO a (1, 2, 3, 4, 5) GO b (1, 2, 3, 4, 5) GO c (1, 2, 3, 4, 5) GO d (1, 2, 3, 4, 5) GO e (1, 2, 3, 4, 5) 

但是,這意味着查詢這個返回我

Go Go Go Go Go a (1, 2, 3, 4, 5) b (1, 2, 3, 4, 5) c (1, 2, 3, 4, 5) d (1, 2, 3, 4, 5) e (1, 2, 3, 4, 5) 

有人可以請解釋這個結果給我,我不明白這一點。

回答

3

如果在字符串的查詢部分忽略的細節,你這樣做:

@query = ' Go ' + @query + 't(...) ' 

@query是從開始空,第一次迭代是:

@query = ' Go ' + '' + 't(...) ' 

這是' Go t(...) '。接下來的迭代變爲:

@query = ' Go ' + ' Go t(...) ' + 't(...)' 

其結束爲' Go Go t(...) t(...) '

如您所見,Go首先添加到字符串中,查詢最後添加,所以最後所有Go都在字符串的開頭。

+0

thanx爲解釋,哥們。現在明白了 – yogi 2013-02-28 07:25:36

4

您需要將其更改爲

select 
@query = 
@query + 
' Go ' +  
tbl1.name + ' (' + 
substring(
(
    select ', ' + tbl2.name 
    from @tbl2 as tbl2 
    for xml path('') 
), 3, 5000) + ') ' 
from @tbl1 as tbl1 
+0

+1快速回復。 thanx – yogi 2013-02-28 07:26:08