将表名传递给存储过程的语句

时间:2015-07-15 15:52:38

标签: tsql

我正在尝试将表名传递给下面的代码,但它无效。代码将在我执行时工作:SELECT X. * INTO dbo.RiskFactors_Tobacco但我无法在以下情况下使其工作:SELECT X. * INTO @RiskFactorsTable。有什么建议吗?

CREATE TYPE typeRiskFactorsTable AS TABLE 
    (RiskFactorICD9 VARCHAR(10)) 

CREATE PROCEDURE dflt.GetRiskFactors 
    @RiskFactorICD9 typeRiskFactorsTable READONLY
    @RiskFactorsTable as VARCHAR(30)
AS

DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
SET @StartDate = '2014-01-01 00:00:00'  
SET @EndDate = '2015-12-31 23:59:59'    

SELECT X.* 
INTO @RiskFactorsTable
FROM 
    (SELECT c.id, ip.AdmitDateTime as DateTime, ip.ICD9Code, ip.ICD9Description, 'IP' as DS
        FROM dbo.Inpat ip
            INNER JOIN dbo.COHORT c ON (c.ID = ip.ID)
            WHERE ip.ICD9Code IN (SELECT RiskFactorICD9 FROM @RiskFactorICD9)
                AND ip.AdmitDateTime between @StartDate and @EndDate 
    UNION ALL
        SELECT c.id, ov.VisitDateTime as DateTime, ov.ICD9Code, ov.ICD9Description, 'OP' as DS
        FROM dbo.Outpat_Visit ov 
            INNER JOIN dbo.Outpat ovd ON (ovd.ID = ov.ID)
            INNER JOIN dbo.COHORT sc ON (c.ID = ov.ID)
            WHERE icd.ICD9Code IN (SELECT RiskFactorICD9 FROM @RiskFactorICD9)
                AND  ov.VisitDateTime between @StartDate and @EndDate  
    ) X
    ORDER BY ID, DateTime, DS
GO

/*TOBACCO*/
DECLARE @RiskFactors typeRiskFactorsTable
INSERT @RiskFactors(RiskFactorICD9) 
    VALUES  ('305.1'), ('989.84'), ('V15.82');
EXEC dflt.GetRiskFactors @RiskFactors, @RiskFactorsTable = RiskFactors_Tobacco;
GO

2 个答案:

答案 0 :(得分:1)

与Zohar在评论中指出的一样,表名不能参数化。此外,如果您正在考虑它,您不能使用表值参数来选择"选择"任

来自MSDN on the INTO clause

  

您不能将表变量或表值参数指定为新表。

你需要选择"选择进入"?你可以做一个" INSERT INTO DestinationTable SELECT ... FROM OriginationTable"?如果可以这样做,那么表值参数应该可以工作。 INTO子句仅适用于您希望select语句同时创建新表并插入其中的情况。

答案 1 :(得分:0)

在程序正文中:

DECLARE @RiskFactorsTable TABLE (RiskFactorsICD9 varchar(10))

然后

INSERT INTO @RiskFactorsTable
SELECT [one column]
FROM [table]

但是您不能将表作为SP参数