26

I have a stored procedure that stores values in a table variable. I select these values and return them when the procedure is called.

I am trying to set these return values in another table variable but I can't figure it out.

Stored procedure

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

Calling code

I call the procedure using:

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')

How can I do this?

Paul White
  • 83,961
  • 28
  • 402
  • 634
ThunD3eR
  • 397
  • 1
  • 3
  • 8

1 Answers1

29

To insert the results into a table, you just want INSERT....EXEC... not the VALUES part of the query.

In your case, this would look like the following:

INSERT INTO @DomainHistory(DomainId,HasHistory)
EXEC GetOrSetDomainId 'test', 'test2';
Mark Sinkinson
  • 10,547
  • 3
  • 46
  • 54