Wednesday, February 20, 2013

Getting the results from a stored procedure into a single variable

I have used both the methods below to put result sets into a single variable.  I will then use that variable as the message body to email the results to myself (or others).

Create Procedure DoSomethingEmailResult

....

I run a bunch of queried looking for data integrity issues, each result set I write into the following table.

    declare @Problems table(
                        SiteId varchar(15) not null,
                        GenId int not null,
                        Alert varchar(max) not null,
                        ProblemDate datetime null default getdate(),
                        AlertLevel varchar(20) null
                )

...

At the end, I want to email the results to myself because I am too lazy to go look for them.

This is how I get a multi-row table worth of results into a single variable.  This becomes the body of my message.

    select @result = coalesce(@result +
        SiteId + char(9) +
        cast(GenId as varchar) + char(9) +
        alert + char(9) +
        AlertLevel + '<br/><br/>','')
        from @problems   


Another query that I have used, but seems a bit more problematic

    set @result = stuff(
    (
    select
        SiteId + char(9) +
        cast(GenId as varchar) + char(9) +
        [Proc] + char(9) +
        alert + char(9) +
        cast(ProblemDate as varchar) +  char(9) +
        AlertLevel + '<br/><br/>'
    from @ErrorTable
    for xml Path(''), Type
    ).value('.', 'varchar(max)'), 0, 1, '');


No comments:

Post a Comment