0

sql server,如果我有这样的表:

id   |    name
-------------
1    |     x
2    |     y
3    |     z

我想创建一个存储过程以在一行中返回结果,如下所示:

x | y | z

我的代码是:

alter PROCEDURE getSupervisorEvaluationPercentages
(
    @FirstSupervisorNumber nvarchar(6),
    @Year int
)
as
DECLARE @Count INT
DECLARE @OptionID INT
DECLARE @getOptionID CURSOR

declare @OptionCountTb table(c int)


SET @getOptionID = CURSOR FOR
    SELECT Id FROM ObjectiveOption
OPEN @getOptionID
FETCH NEXT
    FROM @getOptionID INTO @OptionID
    WHILE @@FETCH_STATUS = 0
    BEGIN
        select @Count = (select COUNT(Id) from EvaluationProcess 
            where FirstSupervisorNumber = @FirstSupervisorNumber and Year = @Year and FirstSupervisorEvaluation = @OptionID)
        insert into @OptionCountTb values(@Count)
        FETCH NEXT
        FROM @getOptionID INTO @OptionID
    END
CLOSE @getOptionID
DEALLOCATE @getOptionID

我想将表格的值显示@OptionCountTb为单行

4

4 回答 4

1

PIVOT 是其中一种方式 http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

于 2012-07-25T09:52:44.487 回答
0

试试这个解决方案:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + [name] 
                    from t01
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
 set @query = 'SELECT ' + @cols + ' from 
             (
                select [name]
                from t01
            ) x
            pivot 
            (
                count([name])
                for name in (' + @cols + ')
            ) p where 1=2 '
print(@query)
execute(@query)
于 2012-07-25T12:04:58.600 回答
0
CREATE TABLE t1(id int,name varchar(10))
INSERT INTO t1
VALUES(1,'x'),
(2,'y'),
(3,'z')

SELECT STUFF((select '|'+name from t1 for XML path('')),1,1,'')
于 2012-07-25T11:05:54.500 回答
0
select 
    name + ' '
from TableName
for xml path('')
于 2012-07-25T09:46:42.463 回答