2

我的问题: SQL Server 2008 中是否可以在存储过程中定义临时表并将其作为变量传递给用户定义的函数?

我需要执行以下操作:

  1. 我有程序dbo.GetMsgCntData

  2. 此过程正在进行一些计算,并且由于此过程,我将数据放入此过程中定义的临时表 ( GetMsgCntData):

    -- table defined in dbo.GetMsgCntData
    DECLARE @tmpTable TABLE (
        ID BIGINT,
        FirstName VARCHAR(50),
        LastName VARCHAR(50),
        UserType varchar(50),
        SenderID bigint,
        IsArchive bit
    )
    
  3. 所以,@tmpTable包含一些数据。我需要运行用户定义的函数GetCnt(@status, @MsgTempTable),但我需要getCnt函数来访问@tmpTable数据。基本上我需要这样的东西:

    -- to be written at the end of dbo.GetMsgCntData
    SELECT cnt(*) total,
        dbo.GetCnt('open', @tmpTable) as opened,
        dbo.GetCnt('closed', @tmpTable) as closed
    FROM @tmpTable
    -- where @tmpTable is temporal table
    
  4. 我试图定义@tableGetCnt用户定义的类型。

    CREATE TYPE dbo.tmp_Messages AS TABLE (
        ID BIGINT,
        FirstName VARCHAR(50),
        LastName VARCHAR(50),
        UserType varchar(50),
        SenderID bigint,
        IsArchive bit
    )
    
    CREATE FUNCTION FUNCTION [dbo].[GetCnt] (
        @Status nvarchar(10),
        @MsgTempTable dbo.tmp_Messages READONLY
    )
    ....
    

但这给了我错误信息:

Operand type clash: table is incompatible with tmp_Messages

我认为我的想法是完全错误的。

4

2 回答 2

2

临时表与用户定义类型不兼容。您应该将临时表声明为用户定义类型:

CREATE TYPE dbo.tmp_Messages AS TABLE 
(
 ID BIGINT,
 FirstName VARCHAR(50),
 LastName VARCHAR(50),
 UserType varchar(50),
 SenderID bigint,
 IsArchive bit
 )
 GO
 --function declaration 

        CREATE FUNCTION [dbo].[GetCnt] (
            @Status nvarchar(10),
            @MsgTempTable dbo.tmp_Messages READONLY
        )...
        -- table defined in dbo.GetMsgCntData
        DECLARE @tmpTable dbo.tmp_Messages;
        INSERT INTO @tmpTable(---some actions

SELECT cnt(*) total,
    dbo.GetCnt('open', @tmpTable) as opened,
    dbo.GetCnt('closed', @tmpTable) as closed
FROM @tmpTable

请阅读一篇关于表值参数的好文章:http: //beyondrelational.com

于 2013-01-29T19:44:25.150 回答
1

您可以使用用户定义的表类型来实现这一点。尝试这个

CREATE TYPE T1Type
AS TABLE (ID BIGINT,
    FirstName VARCHAR(50),
    LastName VARCHAR(50),
    UserType varchar(50),
    SenderID bigint,
    IsArchive bit
)

在你的 SP

DECLARE @tmpTable T1Type
INSERT INTO @tmpTable
SELECT * FROm TableName

在你的功能

CREATE FUNCTION FUNCTION [dbo].[GetCnt] (
    @Status nvarchar(10),
    @MsgTempTable T1Type READONLY
)
于 2013-01-29T19:39:58.693 回答