2016-12-01 48 views
1

我想將多個查詢的結果合併到1個列或變量中。 我有這個疑問: -SQL - 在1個變量或列中合併多個查詢的結果

select Id from EmployeeDetail where Code = 'ABC1' 
select Id from EmployeeDetail where Code = 'ABC2' 

... So On till ABC200 

我想所有的ID在1個可變進一步使用它。

我想用foreach來得到這個。如何在1變量中使用它以用於更進一步的查詢。

我已經嘗試了下面的例子來獲取1個串聯變量中的一個字符串: - 下面的代碼只是一個試驗,它不是在實際查詢上開火。

declare @num int 
declare @num1 VARCHAR(MAX) 

set @num = 1 

declare @results table (val int) 

while (@num < 84) 
begin 
    insert into @results (val) values (@num) 
    set @num = @num + 1 
    set @num1 += '5000' 
    select @num1 
end 
+0

你想Id值爲1,2,3這樣的..? – Mansoor

+0

如果您希望所有行都位於單個字符串中,請參閱(http://stackoverflow.com/questions/15477743/listagg-in-sqlserver)。但是你打算在另一個查詢中使用它......那麼組合形式對你真的很有用嗎?您可能想要迭代第一個結果集。 –

+0

添加最後的預期輸出是什麼?你想得到結果或者在共同分離時分配varibale –

回答

1

如果您正在獲取全部匹配某種模式的EmployeeDetail代碼,那麼你可以達到你想要使用下面的簡單查詢的內容:

declare @AllIDs varchar(max) 
set @AllIDs = '' 

select 
    @AllIDs = (@AllIDs + cast(ID as varchar(10)) + ',') 
from EmployeeDetail WHERE Code like 'ABC%' 

在運行它,變量@AllIDs將包含以','分隔的所有ID。

+0

它在'='附近顯示錯誤的語法。 – Anup

+0

告訴我錯誤在這裏: - AllIDs = AllIDs – Anup

+0

@Anup這是因爲你在數據庫中使用SQL 2005或SQL 2008兼容性。查看更新後的答案。我針對SQL 2008 R2成功運行了原始版本。 – andrews

0

據我所知,你想連接所有ID的結果與代碼ABC1,ABC2,.. ABC200。檢查下面的解決方案,並希望它可以幫助你。

declare @num int 
declare @text VARCHAR(MAX) 

set @text = 'ABC' 
set @num = 1 

declare @results table (val varchar(10)) 

while (@num <= 200) 
begin 
    insert into @results (val) values (@text + cast(@num as varchar(3))) 
    set @num = @num + 1 
end 

Select ID from EmployeeDetail where Code in (Select val from @results) 
0

問題都分佈在兩個部分

  1. 生成變量的值。
  2. 對步驟1上生成的數據進行過濾結果。

    --Step 1 
    
    declare @num int 
    declare @text VARCHAR(MAX) 
    
    set @text = 'ABC' 
    set @num = 1 
    
    declare @results table (val varchar(10)) 
    
    while (@num <= 200) 
    begin 
        insert into @results (val) values (@text + cast(@num as varchar(3))) 
        set @num = @num + 1 
    end 
    
    --Step 2 
    
    Select ID from EmployeeDetails e 
    inner join @results r on r.val=e.Code 
    
0
-- Prepare the data 
DECLARE @EmployeeDetail TABLE (Id int identity(1,1), Code varchar(10)) 
INSERT @EmployeeDetail VALUES ('ABC1'), ('ABC2'), ('DEF'), ('ABC3') 

DECLARE 
    @CodePattern varchar(10) = 'ABC', 
    @RangeFrom int = 1, 
    @RangeTo int = 200 

DECLARE @Ids varchar(max) = (SELECT STUFF((
    SELECT ',' + CAST(Id AS varchar(10)) 
    FROM @EmployeeDetail 
    WHERE 
     -- The pattern of the code is prefix + number 
     -- Can use LIKE and BETWEEN to replace your multiple query 
     code LIKE @CodePattern + '%' 
     AND SUBSTRING(code, LEN(@CodePattern) + 1, 10) BETWEEN @RangeFrom AND @RangeTo 
    FOR XML PATH('') 
), 1, 1, '')) 

PRINT @Ids