EF can't infer return schema from Stored Procedure selecting from a #temp table

后端 未结 4 1853
迷失自我
迷失自我 2020-11-27 03:02

Suppose the following:

CREATE PROCEDURE [MySPROC]
AS 
BEGIN

CREATE TABLE #tempSubset(
    [MyPrimaryKey] [bigint]  NOT NULL,
    [OtherColumn]  [int]     NO         


        
4条回答
  •  Happy的楠姐
    2020-11-27 03:33

    CREATE PROCEDURE [MySPROC]
    AS 
    BEGIN
    
    --supplying a data contract
    IF 1 = 2 BEGIN
        SELECT
            cast(null as bigint)  as MyPrimaryKey,
            cast(null as int)    as OtherColumn
        WHERE
            1 = 2  
    END
    
    CREATE TABLE #tempSubset(
        [MyPrimaryKey] [bigint]  NOT NULL,
        [OtherColumn]  [int]     NOT NULL)
    
    INSERT INTO #tempSubset (MyPrimaryKey, OtherColumn) 
        SELECT SomePrimaryKey, SomeColumn 
        FROM   SomeHugeTable
        WHERE  LimitingCondition = true
    
    SELECT MyPrimaryKey, OtherColumn 
    FROM   #tempSubset
    WHERE  SomeExpensiveCondition = true
    
    END
    

    Supplying a faux data contract for the result set is the easiest, cleanest and fastest way to take care of the issue. This same problem exists in data source controls in SSIS too. .NET will read the result set from the unreachable "contract" section of the query and supply the metadata for the complex type. No performance impact and no need to comment out the SQL that does the actual work.

提交回复
热议问题