2010-07-08 83 views
3

我試圖生成一系列字母的,使用SQL Server。字母序列生成的SQL Server

假設我有一個表如下

DECLARE @Funding TABLE (FundingDetailID INT,FundingID INT, DetailDescription VARCHAR(50)) 
INSERT INTO @Funding (FundingDetailID ,FundingID , DetailDescription) VALUES (1,107,'Desc 1') 
INSERT INTO @Funding (FundingDetailID ,FundingID , DetailDescription) VALUES (1,107,'Desc 2') 
INSERT INTO @Funding (FundingDetailID ,FundingID , DetailDescription) VALUES (1,107,'Desc 3') 

我試圖得到下面的結果。

a) Desc 1 
b) Desc 2 
c) Desc 3 

如何生成「a)」, 「b)」, ...?我不允許添加任何額外的臨時表或表變量來存儲最初的字母。它們應該被生成。

這是要在SQL Server 2005中完成的。

有什麼想法?

感謝

Lijo Cheeran約瑟夫

+2

這是功課?如果是這樣,請將其標記爲 – 2010-07-08 18:32:16

+0

是否僅限於26個項目? – kennytm 2010-07-08 18:35:56

+0

是的,它僅限於26 – Lijo 2010-07-08 18:43:32

回答

6

使用ROW_NUMBER()如下

DECLARE @Funding TABLE (FundingDetailID INT,FundingID INT, DetailDescription VARCHAR(50)) 
INSERT INTO @Funding VALUES (1,107,'Desc 1') 
INSERT INTO @Funding VALUES (1,107,'Desc 2') 
INSERT INTO @Funding VALUES (1,107,'Desc 3') 

SELECT CHAR (CAST (96+ROW_NUMBER() OVER (Order BY FundingDetailID) AS VARCHAR)) + ') ' + DetailDescription 
FROM @Funding 



----------------------------------------------------- 
a) Desc 1 
b) Desc 2 
c) Desc 3 
+0

+1:詛咒 - 你偷走了我的答案! :) – 2010-07-08 18:41:29

+0

謝謝。以下也將工作,對吧? SELECT CHAR(CAST(96 + ROW_NUMBER()OVER(ORDER BY DetailDescription)AS VARCHAR))+ ')' + DetailDescription FROM @Funding – Lijo 2010-07-08 18:48:07

0

拉吉更已經發布的row_number(),而我寫它。我投了他的答案,但這是我的變種,在桌子上做了更新,以防萬一你對此感興趣。

update f1 
set  f1.DetailDescription = char(96 + f2.rn) + ') ' + f2.DetailDescription 
from @Funding f1 
join (
     select row_number() over (order by FundingDetailId, 
             FundingId, DetailDescription) as rn 
     ,  * 
     from @Funding f 
     ) f2 
on  f1.FundingDetailID = f2.FundingDetailID 
     and f1.FundingID = f2.FundingID 
     and f1.DetailDescription = f2.DetailDescription 

select * 
from @Funding