0

In sql server, if I have a table like this :

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

I want to create a stored procedure to return the result in one row like this :

x | y | z

my code is :

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

I want to display the values of the table @OptionCountTb as single row

1

4 Answers 4

1

PIVOT is one of the ways http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

Sign up to request clarification or add additional context in comments.

Comments

0
select 
    name + ' '
from TableName
for xml path('')

1 Comment

but I want each value to appear as a separate cell
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,'')

Comments

0

try this solution:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.