sql-server – 通过存储过程从数据库中检索值

我有这个数据库与表’crigsStaffActivity’.我设法检索值并显示它.但结果并没有表现出我的期望.

用值创建表的脚本

CREATE TABLE [dbo].[crigsStaffActivity]
(
    [projectRef] [varchar](200) NOT NULL,
    [activityLine] [int] NOT NULL,
    [cost] [real] NOT NULL,
    [staffCost] [varchar](500) NOT NULL
) ON [PRIMARY]
GO

INSERT [dbo].[crigsStaffActivity] ([projectRef], [activityLine], [cost], [staffCost]) 
VALUES (N'MRC/CRIGS/330', 1, 1, N'ProjectLeader'),
       (N'MRC/CRIGS/330', 2, 2, N'Research Collaborators'),
       (N'MRC/CRIGS/330', 1, 1, N'Project Collaborators'),
       (N'MRC/CRIGS/330', 2, 2, N'Project Collaborators'),
       (N'MRC/CRIGS/330', 2, 3, N'Research/Project Assistant');

ALTER TABLE [dbo].[crigsStaffActivity] 
    ADD CONSTRAINT [DF__crigsStaff__cost__5535A963] DEFAULT ((0)) FOR [cost]
GO

表格截图:

《sql-server – 通过存储过程从数据库中检索值》

我的存储过程:

ALTER PROCEDURE [dbo].[getCrigsStaffActivity] 
    @ProjectRef AS VARCHAR(1000),
    @staffCost AS varchar(1000)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @val AS VARCHAR(2000);
    SET @val='';

    DECLARE @temp AS VARCHAR(2000);
    DECLARE @activityLine AS VARCHAR(2000);
    DECLARE @cost AS VARCHAR(2000);
    DECLARE @ref as CURSOR;   

    SET @ref = CURSOR FOR
        SELECT activityLine, cost
        FROM crigsStaffActivity
        WHERE projectRef = @ProjectRef
          AND staffCost = @staffCost

    OPEN @ref;

    FETCH NEXT FROM @ref INTO @activityLine, @cost;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        FETCH NEXT FROM @ref INTO @activityLine, @cost;
        SET @val = CONCAT(@activityLine,',',@cost);
    END

    CLOSE @ref;
    DEALLOCATE @ref;

    SELECT @val AS ref;
END

当我执行存储过程时,我得到这个结果:

ref
----
2,2

问题是,对于项目协作者,我有两个重复值,因此我需要得到这样的结果:

ref 
-----
1,1
2,2

我的问题是如何实现上述结果.

这个存储过程的更好结果可能是:

ref
-----------------------------
1,1,ProjectLeader
2,2,Research collaborators
1,1,Project collaborators
2,2,Project collaborators
2,3,Research/Project Assistant

最佳答案 如果我弄错了.你不需要使用光标.

ALTER PROCEDURE [dbo].[getCrigsStaffActivity] 
    @ProjectRef AS VARCHAR(1000),
    @staffCost AS varchar(1000)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT CONCAT(activityLine,',', cost,',', staffCost) as ref
        FROM crigsStaffActivity
        WHERE projectRef = @ProjectRef
          AND staffCost = @staffCost


END
点赞