日期和表名称作为动态SQL中的参数

时间:2014-06-10 18:49:16

标签: sql sql-server variables stored-procedures dynamic

我正在尝试创建一个存储过程,允许我选择一个开始日期和结束日期来获取数据,并有一个变量表名来写这个数据。

我想将两个日期和表名作为参数传递给存储过程。这是我坚持的部分。我拿出存储过程尝试让它工作。通过这种方式,我可以看到错误所在的行。

DECLARE @MinDateWeek DATETIME
SELECT @MinDateWeek= DATEADD(WEEK, DATEDIFF(WEEK,0,GETDATE()), -7)
DECLARE @MaxDateWeek DATETIME
SELECT @MaxDateWeek= DATEADD(WEEK, DATEDIFF(WEEK,0,GETDATE()),0)
DECLARE @SQLCommand NVARCHAR(MAX)

    SET @SQLCommand = ' --ERROR ON THIS LINE
-- Getting how much space is used in the present
    DECLARE @Present Table (VMName NVARCHAR(50), UseSpace float(24))
    INSERT INTO @Present 
        SELECT  VMName
            ,SUM(CapacityGB-FreeSpaceGB)  
        FROM VMWareVMGuestDisk 

        GROUP BY VMName;
    -- Getting how much space was used at the reference date

    DECLARE @Past Table (VMName NVARCHAR(50), UseSpace float(24))
    INSERT INTO @Past
        SELECT  VMName
            ,SUM(CapacityGB-FreeSpaceGB)  
        FROM VMWareVMGuestDisk 
        WHERE Cast([Date] AS VARCHAR(20))= '''+CAST(@MinDateWeek AS varchar(20))+'''
        GROUP BY VMName;

    --Inserting the average growth(GB/DAY) between the 2 dates in a Temporary Table

    CREATE TABLE #TempWeek (VMName NVARCHAR(50) 
                    , CapacityGB float(24)
                    , GrowthLastMonthGB float(24)
                    , FreeSpace FLOAT(24) )

    INSERT INTO #TempWeek
    SELECT DISTINCT V.VMName
        ,SUM(V.CapacityGB)
        ,SUM(((W1.UseSpace-W2.UseSpace)/(DATEDIFF(DAY,'''+CONVERT(VARCHAR(50),@MaxDateWeek)+''','''+CONVERT(VARCHAR (50),@MaxDateWeek)+'''))))
        ,SUM(V.FreeSpaceGb)
    FROM VMWareVMGuestDisk AS V
        LEFT JOIN
        @Present AS W1
        ON
        V.VMName=W1.VMName
        LEFT JOIN
        @Past AS W2
        ON
        W1.VMName=W2.VMName
    WHERE (CONVERT(VARCHAR(15),Date))='''+CONVERT(VARCHAR(50),@MaxDateWeek)+'''
    GROUP BY V.VMName;

    -- Checking if there is already data in the table

            TRUNCATE TABLE SAN_Growth_Weekly;

    --insert data in permanent table
    INSERT INTO SAN_Growth_Weekly (VMName,Datacenter,Cluster,Company,DaysLeft,Growth,                                                             Capacity,FreeSpace,ReportDate)
        SELECT DISTINCT
            G.VMName
            ,V.Datacenter
            ,V.Cluster
            ,S.Company
            , DaysLeft = 
            CASE 
                WHEN G.GrowthLastMonthGB IS NULL 
                    THEN ''NO DATA''
                WHEN (G.GrowthLastMonthGB)<=0 
                    THEN ''UNKNOWN''
                WHEN (G.FreeSpace/G.GrowthLastMonthGB)>0 AND (G.FreeSpace/G.GrowthLastMonthGB) <=30 
                    THEN ''Less then 30 Days''
                WHEN (G.FreeSpace/G.GrowthLastMonthGB)>30 AND (G.FreeSpace/G.GrowthLastMonthGB)<=60                                 THEN ''Less then 60 Days''
                WHEN (G.FreeSpace/G.GrowthLastMonthGB)>60 AND (G.FreeSpace/G.GrowthLastMonthGB)<=90 
                    THEN ''Less then 90 Days''
                WHEN (G.FreeSpace/G.GrowthLastMonthGB)>90 AND (G.FreeSpace/G.GrowthLastMonthGB)<=180                                THEN ''Less then 180 Days''
                WHEN (G.FreeSpace/G.GrowthLastMonthGB)>180 AND (G.FreeSpace/G.GrowthLastMonthGB)<=365                               THEN ''Less then 1 Year''
                ELSE ''Over 1 Year''
            END
            ,G.GrowthLastMonthGB
            ,G.CapacityGB
            ,G.FreeSpace
            ,'''+@MaxDateWeek+'''
        FROM #tempWeek AS G
        RIGHT JOIN VMWareVMGuestDisk AS V
            ON V.VMName = G.VMName COLLATE SQL_Latin1_General_CP1_CI_AS
        LEFT JOIN Server_Reference AS S
            ON G.VMName COLLATE SQL_Latin1_General_CP1_CI_AS=S.[Asset Name]
        WHERE '''+CONVERT(VARCHAR(50),@MaxDateWeek)+'''= CONVERT(VARCHAR(50),V.Date);'

    EXEC sp_executesql @SQLCommand;

我得到的错误是

  

从字符转换日期和/或时间时转换失败   字符串。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

您是否忘记在动态sql中附上Group By?:

ALTER PROCEDURE SAN_DISK_GROWTH
    @MaxDateWeek DATETIME ,
    @MinDateWeek DATETIME
AS
    BEGIN
        DECLARE @SQLCommand NVARCHAR(MAX)
        SELECT  @SQLCommand = '
    DECLARE @Present Table (VMName NVARCHAR(50), UseSpace float(24))
    INSERT INTO @Present 
        SELECT  VMName
            ,SUM(CapacityGB - FreeSpaceGB)  
        FROM VMWareVMGuestDisk 
        WHERE CONVERT(VARCHAR(15),Date) = '''
                + CONVERT(VARCHAR(50), @MaxDateWeek) + ''' GROUP BY VMName;'

    END

答案 1 :(得分:0)

尝试将日期/时间值指定为动态SQL查询的参数。换句话说,不是将日期转换为varchar,而是使用查询中的参数:

WHERE @MaxDateWeek = V.Date;

并将调用的参数传递给sp_executesql,如下所示:

EXEC sp_executesql @SQLCommand,
    '@MindateWeek datetime, @MaxDateWeek datetime',
    @MinDateWeek = @MinDateWeek,
    @MaxDateWeek = @MaxDateWeek

然后您不必将日期转换为字符串。

请注意,这不适用于动态表名或列名。这些需要作为动态SQL本身的一部分连接在一起。

例如,如果你有一个像这样的表名变量:

declare @TableName sysname
set @TableName = 'MyTable'

并且您希望动态SQL从该表中检索数据,然后您需要构建这样的FROM语句:

set @SQLCommand = N'SELECT ...
    FROM ' + @TableName + N' WHERE...

这样就可以将名称构建到SQL中:

'SELECT ... FROM MyTable WHERE...'