SQL Server中的字母系列生成

时间:2010-07-08 18:27:32

标签: sql sql-server sql-server-2005

我正在尝试使用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 Joseph

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

Raj在我写这篇文章时已经发布了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