需要有关SQL查询的帮助

时间:2011-06-03 06:43:09

标签: sql dynamic-sql

我需要查询帮助。在我的查询中,我想将我的表名作为参数传递。这是我的问题:

SELECT DISTINCT 
    CONVERT (varchar, InspectDateTime) AS 'Inspect Date Time', 
    CONVERT (varchar, SynDateTime) AS 'Sync Date Time', 
    Employee, 
    ROUND(OverAllPercentage, 2) AS Grade 
FROM 
    Table_Name 
WHERE 
    (DATEADD(dd, DATEDIFF(dd, 0, InspectDateTime), 0) 
    BETWEEN 
        DATEADD(dd, DATEDIFF(dd, 0, @From ), 0) AND 
        DATEADD(dd, DATEDIFF(dd, 0, @To ), 0)) 
ORDER BY 
    'Inspect Date Time'

这里我想传递Table_Name作为参数。请注意,此查询已将两个aurguments作为参数,即"@From“和”@To

此致 阿卜杜拉

4 个答案:

答案 0 :(得分:3)

在SQL Server中,如果要“参数化”表名,则必须使用动态SQL

如果是这样,你必须阅读 Erland的The Curse and Blessing of dynamic SQL作为介绍。

基本上,您需要将SQL语句构建为字符串,然后执行它。没有其他方法可以在SQL Server T-SQL语句中“参数化”表名。

答案 1 :(得分:3)

好的,假设您正在使用SQL Server(根据DATEADDDATEDIFF函数判断),您需要

  1. 构造一个连接的sql命令 作为字符串(注意不要允许 SQL注入:即你应该检查 你的table_name变量是一个 查找有效的表名 可能的名称形式 information_schema并验证 等)

  2. 使用执行动态sql sp_executesqlhttp://msdn.microsoft.com/en-us/library/ms188001.aspx

答案 2 :(得分:3)

如果您正在使用MS SQL,则可以执行以下操作:

CREATE PROCEDURE sp_GetMyStuff
(
    @From datetime,
    @To datetime,
    @TableName nvarchar(100)
)
AS

exec('    
    SELECT DISTINCT 
        CONVERT (varchar, InspectDateTime) AS ''Inspect Date Time'', 
        CONVERT (varchar, SynDateTime) AS ''Sync Date Time'', 
        Employee, 
        ROUND(OverAllPercentage, 2) AS Grade 
    FROM 
        ' + @TableName + ' 
    WHERE 
        (DATEADD(dd, DATEDIFF(dd, 0, InspectDateTime), 0) 
        BETWEEN 
            DATEADD(dd, DATEDIFF(dd, 0, ' + @From + '), 0) AND 
            DATEADD(dd, DATEDIFF(dd, 0, ' + @To + '), 0)) 
    ORDER BY 
        1
');

然后只是称之为

sp_GetMyStuff '2011-05-05', '2011-06-05', 'TBL_MYTABLE'

答案 3 :(得分:0)

谢谢balexandre。经过微小修改(将@ From,@ To转换为varchar)后的最终查询是:

CREATE PROCEDURE sp_GetMyStuff

@TableName VARCHAR(128),
@From DATETIME,
@To DATETIME

AS

DECLARE @sql VARCHAR(4000)
SELECT @sql = 'SELECT DISTINCT CONVERT (varchar, InspectDateTime) AS ''Inspect Date Time'', CONVERT (varchar, SynDateTime) AS ''Sync Date Time'', Employee, ROUND(OverAllPercentage, 2) AS Grade
FROM ' + @TableName + '
WHERE
(DATEADD(dd, DATEDIFF(dd, 0, InspectDateTime), 0) BETWEEN DATEADD(dd, DATEDIFF(dd, 0,'''+ CAST(@From AS VARCHAR(100)) +''' ), 0)
AND DATEADD(dd, DATEDIFF(dd, 0,'''+ CAST(@To AS VARCHAR(100)) +'''), 0))
ORDER BY ''Inspect Date Time'''
EXEC (@sql)

GO