从存储过程中的列运行SQL查询

时间:2015-03-02 06:33:02

标签: sql sql-server sql-server-2008 stored-procedures

我有一个包含查询的列的表来计算。我正在编写一个存储过程来从该表中获取记录。我需要做的是在count列中执行查询并在同一列中返回值。下面是一个带有计数列的示例表。

所以,当我运行存储过程时,我应该得到如下结果:

enter image description here

那么,如果有任何方法可以在sql server 2008中实现它,请你建议我。

2 个答案:

答案 0 :(得分:1)

尽管这种设计很糟糕,但是你可以按照自己的方式做到这一点:

CREATE TABLE Users(ID int)
GO

CREATE TABLE Test(ID INT, Name NVARCHAR(20), Count NVARCHAR(200))
GO

INSERT  INTO Users
VALUES  ( 1 ),
        ( 1 ),
        ( 2 ),
        ( 3 )

INSERT  INTO Test
VALUES  ( 1, 'A', 'Select Count(*) From Users where ID = 1' ),
        ( 2, 'B', NULL ),
        ( 3, 'C', 'Select Count(*) From Users where ID = 3' ),
        ( 4, 'D', 'Select Count(*) From Users where ID = 1' )


DECLARE @Results TABLE
    (
      ID INT ,
      Name NVARCHAR(20) ,
      Count INT
    )
DECLARE @R TABLE ( ID INT )
DECLARE @ID INT ,
    @Name NVARCHAR(20) ,
    @Statement NVARCHAR(200) ,
    @Count INT

DECLARE cur CURSOR FAST_FORWARD READ_ONLY
FOR
    SELECT  ID , Name , Count FROM    Test

OPEN cur

FETCH NEXT FROM cur INTO @ID, @Name, @Statement

WHILE @@FETCH_STATUS = 0
    BEGIN

        DELETE  FROM @R

        INSERT  INTO @R
                EXEC ( @Statement )

        INSERT  INTO @Results
        VALUES  ( @ID, @Name, ( SELECT  * FROM    @R ) )  

        FETCH NEXT FROM cur INTO @ID, @Name, @Statement

    END

CLOSE cur
DEALLOCATE cur

SELECT  * FROM    @Results

输出:

ID  Name  Count
1   A     2
2   B     NULL
3   C     1
4   D     2

答案 1 :(得分:0)

我同意Sorrel Vesper。我不明白为什么要在表中存储查询。

而不是使用/创建适当的SP:

CREATE PROCEDURE GetUserCount
    @userId INT
AS
BEGIN

    SET NOCOUNT ON;
    SELECT COUNT(*) AS UserCount
    FROM TableName
    WHERE UserId = @userId

END

有关详细信息,请参阅:CREATE PROCEDURE

如果您想为每个用户获取数据,请使用以下查询:

SELECT UserId, COUNT(*)
FROM TableName
GROUP BY UserId

这就是全部!

有关详细信息,请参阅:Aggregate functions