使用字符串变量替换存储过程中的SQL Server子查询

时间:2018-03-07 15:55:42

标签: sql-server stored-procedures exec temp-tables

CREATE PROCEDURE CreateAsset 
    @NumeratorQuery AS TEXT,
    @DenominatorQuery AS TEXT,
    @family AS VARCHAR(255),
    @control_num AS VARCHAR(255),
    @metric_sequence AS VARCHAR(255)
AS
    -- Drop Temporary Tables if they exist
    IF OBJECT_ID('tempdb.dbo.#TempNumerator') IS NOT NULL
        DROP TABLE tempdb.dbo.#TempNumerator

    IF OBJECT_ID('tempdb.dbo.#TempDenominator') IS NOT NULL
        DROP TABLE tempdb.dbo.#TempDenominator

    IF OBJECT_ID('tempdb.dbo.#TempAssets') IS NOT NULL
        DROP TABLE tempdb.dbo.#TempAssets

    IF OBJECT_ID('tempdb.dbo.#TempSummary') IS NOT NULL
        DROP TABLE tempdb.dbo.#TempSummary

    -- Create Temporary Numerator Table
    SELECT * 
    INTO #TempNumerator 
    FROM
        (SELECT DISTINCT AssetID 
         FROM openquery(RISKFABRIC_SACS_PROD, 'SELECT computer_name AS AssetID
                                               FROM SACS_PROD.assets 
                                               WHERE (device_type = "SERVER" OR 
                                                      device_type = "INDETERMINATE" OR 
                                                      device_type = "VIRTUAL MACHINE") 
                                                 AND (status = "ACTIVE (PER DOCUMENTATION)" OR status="ACTIVE (DEFINITIVE)")')
            ) AS #TempNumerator
.
.
.

在上面的存储过程中,我想用@NumeratorQuery替换子查询中的所有内容,如下所示:

SELECT * 
INTO #TempNumerator 
FROM (@NumeratorQuery) AS #TempNumerator

如何实现这一目标?

3 个答案:

答案 0 :(得分:0)

如果我理解你的问题,它将如下所示:

Create Table #TempNumerator
(
    field list...
)

insert into #TempNumerator
exec (@NumeratorQuery)

答案 1 :(得分:0)

DECLARE@NumeratorQuery NVARCHAR(500)
    SET@NumeratorQuery ='SELECT DISTINCT AssetID
    FROM openquery(RISKFABRIC_SACS_PROD,'SELECT computer_name AS AssetID
    FROM SACS_PROD.assets
    WHERE(device_type="SERVER"OR
    device_type="INDETERMINATE"OR
    device_type="VIRTUAL MACHINE")
    AND(status="ACTIVE (PER DOCUMENTATION)"OR status="ACTIVE (DEFINITIVE)")'

    EXEC(@NumeratorQuery)

答案 2 :(得分:0)

我找到了问题的真正根本原因。旧版本的MSSQL不支持将EXEC放在SELECT INTO语句的FROM子句中,但我读过的新版本支持它。

SELECT * 
INTO #TempNumerator 
FROM EXEC(@NumeratorQuery) AS #TempNumerator

这才是真正的根本原因;插入语句不存在相同的限制,因此,这非常有效:

CREATE TABLE #TempNumerator (AssetID VARCHAR(255))
INSERT INTO #TempNumerator EXEC(@NumeratorQuery)