开发者

Insert Into temp table from a stored procedure that returns multiple result sets

Consider the following sql

A stored proc called myProc which returns two result sets. Result set 1 returns column1, column2. Result set 2 re开发者_如何学Cturns column 3, column 4, column 5.

The following sql will fail since the temp table only has defined 2 int columns.

Create Table #temp1(
Column1 int,
Column2 int)

insert into #temp1 exec myProc

My question is is it possible to just insert the first result set into #temp1?


Old post, but I faced the same problem and although the answers mentioned above are a bit related, the OP's question is about SP that returns multiple sets. The only solution I could find, apart from rewriting the SP to split it into smaller SPs, was to write a SQL CLR procedure that executes the SP and returns only the required result set. The procedure gets the index of the required result set, executes a SqlCommand to run the intial T-SQL SP, then loops through a SqlDataReader results until it finds the desired result set and returns the corresponding records. The following code is part of the SQL CLR procedure:

SqlDataReader rdr = command.ExecuteReader();
int index = 0;
bool bContinue = true;
while (index < resultSetIndex.Value)
{
    if (!rdr.NextResult())
    {
        bContinue = false;
        break;
    }
    index++;
}
if (!bContinue)
    throw new Exception("Unable to read result sets.");

.......

List<SqlMetaData> metadataList = new List<SqlMetaData>();
for (int i = 0; i < rdr.FieldCount; i++)
{
    string dbTypeName = rdr.GetDataTypeName(i);
    SqlMetaData metadata;
    if (dbTypeName.ToLower().Contains("char"))
        metadata = new SqlMetaData(rdr.GetName(i), (SqlDbType)Enum.Parse(typeof(SqlDbType), dbTypeName, true), 50);
    else
        metadata = new SqlMetaData(rdr.GetName(i), (SqlDbType)Enum.Parse(typeof(SqlDbType), dbTypeName, true));
    metadataList.Add(metadata);
}
SqlDataRecord record = new SqlDataRecord(metadataList.ToArray());
object[] values = new object[rdr.FieldCount];
if (rdr.HasRows)
{
    SqlContext.Pipe.SendResultsStart(record);
    while (rdr.Read())
    {
        rdr.GetValues(values);
        record.SetValues(values);
        SqlContext.Pipe.SendResultsRow(record);
    }
    SqlContext.Pipe.SendResultsEnd();
}


There's another way

SELECT * into #temp 
  from OPENROWSET('SQLNCLI', 'Server=(local)\\(instance);Trusted_Connection=yes;',
'EXEC (database).(schema).(sproc)')

This'll insert the first resultset into #temp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜