㈠ SQL中一條查詢語句,得到一列多個結果,現在想用一個變數存儲起來,並用;分開,請問如何處理呢
--先將表倒入臨時表,方便自已加工,這里加了一個 num 欄位來記錄狀態
select email,1 num into #email from where id=1
--定義一些變數,@email是你需要的,@tmpemail 用來臨時存儲判斷條件的
declare @i int,@n int,@email varhcar(8000),@tmpemail varchar(100)
set @email=''
set @i=1
select @n=count(*) from #email
--使用循環獲取email,賦值給@email
while @i<=@n
begin
if @email='' then
begin
select top 1 @email=email,@tmpemail=email from #email where num=1 order by email
end
else
begin
select top 1 @email=@email+';'+email,@tmpemail=email from #email where num=1 order by email
end
--將已獲取過的記錄做標記,將num欄位改為0
update #email set num=0 where num=1 and email=@tmpemail
set @i=@i+1
end
--輸出變數@email
select @email
drop table #email