将存储过程的结果插入表变量


12

我有一个存储过程,将值存储在表变量中。我选择这些值并在调用过程时将其返回。

我试图在另一个表变量中设置这些返回值,但我无法弄清楚。

存储过程

ALTER PROCEDURE [dbo].[GetOrSetDomainId]
@DomainName varchar(50),
@DomainUrl varchar(50)
AS
BEGIN
    DECLARE @DomainId bigint;
    DECLARE @NumberOfRwos bigint;

    DECLARE @DomainHistory TABLE
    (
        DomainId bigint, 
        HasHistory bit,
        ServerOnline bit,
        DatabaseOnline bit, 
        ServerPerformance bigint,
        DatabasePerformance bigint, 
        SoldTickets bigint
    )


    SELECT  @NumberOfRwos =  COUNT(Id) 
    FROM DomainData
    WHERE DomainName = @DomainName OR DomainUrl = @DomainUrl

    IF(@NumberOfRwos = 0)
    BEGIN
        INSERT INTO DomainData (DomainName, DomainUrl) VALUES (@DomainName, @DomainUrl)

         SELECT @DomainId =  @@IDENTITY

         INSERT INTO @DomainHistory(DomainId,HasHistory)VALUES(@DomainId, 0)

         SELECT * FROM @DomainHistory
    END

    ELSE
    BEGIN
    ---not important here----
    END

END

呼叫码

我使用以下方法调用该过程:

DECLARE @DomainHistory TABLE
(
    DomainId bigint, 
    HasHistory bit,
    ServerOnline bit,
    DatabaseOnline bit, 
    ServerPerformance bigint,
    DatabasePerformance bigint, 
    SoldTickets bigint
)

SET @DomainHistory = EXEC GetOrSetDomainId 'test', 'test2'
---Other alternatives:---
INSERT INTO @DomainHistory(DomainId,HasHistory)
VALUES(EXEC GetOrSetDomainId 'test', 'test2')

我怎样才能做到这一点?


附带说一下,@@IDENTITY当涉及到触发器时,可以给出意外的值。 SCOPE_IDENTITY()通常是最好的。 更多
所有行业的乔恩

Answers:


14

要将结果插入表中,您只需要查询INSERT....EXEC...VALUES一部分。

您的情况如下所示:

INSERT INTO @DomainHistory(DomainId,HasHistory)
EXEC GetOrSetDomainId 'test', 'test2';
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.