2011-08-17 234 views
2

时,我已经写了下面的存储过程转换日期时间错误:执行SQL存储过程

GO 
/****** Object: StoredProcedure [dbo].[ReadCounters] Script Date: 08/17/2011 13:43:12 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

-- ReadCounters -- 
ALTER PROCEDURE [dbo].[ReadCounters] 
    @type bit, 
    @startDate DateTime, 
    @endDate DateTime 
AS 
BEGIN 
    DECLARE 
    @AllCounterIds NVARCHAR(MAX), 
    @Query NVARCHAR(MAX); 

    SELECT @AllCounterIds = STUFF((
      SELECT DISTINCT '],[' + CAST([CounterId] AS VARCHAR(32)) 
      FROM AllCounters 
      WHERE [DateTime] > @startDate AND [DateTime] < @endDate AND [Type] = @type 
      for xml path('')), 1, 2, '') + ']'; 

    SET @Query = 'SELECT [DateTime], pvt.* from 
        (SELECT [Type], [DateTime], [Value], [CounterId] 
        FROM AllCounters WHERE CounterId IN 
         (
         SELECT DISTINCT([CounterId]) 
         FROM AllCounters 
         WHERE [DateTime] > '''+ @startDate +''' AND [DateTime] < '''+ @endDate +''' AND [Type] = '+ @type +' 
         ) AND [DateTime] > '''+ @startDate +''' AND [DateTime] < '''+ @endDate +''' AND [Type] = '+ @type +' 
        ) S 
       PIVOT 
       (
        SUM (Value) 
        FOR CounterId IN 
        (' + @AllCounterIds + ') 
       ) AS pvt;';   
    EXECUTE(@Query); 
END 

现在,当我尝试使用执行该SP以下任一方式:

exec ReadCounters 1,'2013-10-05', '2011-11-30' 
exec ReadCounters 1,'2013-10-05 00:00:00', '2011-11-30 00:00:00' 
exec ReadCounters 1,'2013-10-05 00:00:00.000', '2011-11-30 00:00:00.000' 
exec ReadCounters 1,{ts '2013-10-05 00:00:00.000'}, {ts '2011-11-30 00:00:00.000'} 

我获得以下错误:

Msg 241, Level 16, State 1, Procedure ReadCounters, Line 19 
Conversion failed when converting date and/or time from character string. 

任何建议为什么给我错误。如果只执行Select查询,它运行得很好。

+0

仍然得到同样的错误... – 2011-08-17 13:20:18

+0

退房GBN的答案 - 这是否什么帮助? – 2011-08-17 13:21:32

+0

@marc_s yup gbn的回答是正确的...... – 2011-08-17 13:38:57

回答

3

你当然需要CONVERT对其进行格式化

.... 
WHERE [DateTime] > '''+ CONVERT(varchar(30), @startDate, 120) +''' AND ... 
... 

为什么SQL SERVER 猜测你想连接不同的数据类型?

这个错误是因为NVARCHAR(MAX)为低优先级的日期时间,然后按these rules

2

我宁愿做这一点 - 节省了大量凌乱的转换和红/黑休息(虽然我仍然会建议串联为ID的逗号分隔的列表):

SET @Query = N'SELECT [DateTime], pvt.* from 
      (SELECT [Type], [DateTime], [Value], [CounterId] 
      FROM AllCounters WHERE CounterId IN 
       (
       SELECT DISTINCT([CounterId]) 
       FROM AllCounters 
       WHERE [DateTime] > @startDate AND [DateTime] < @endDate AND [Type] = @type 
       ) AND [DateTime] > @startDate AND [DateTime] < @endDate AND [Type] = @type 
      ) S 
      PIVOT 
      (
       SUM (Value) 
       FOR CounterId IN 
       (' + @AllCounterIds + ') 
      ) AS pvt;';   

EXEC sp_executesql @query, 
    N'@startDate DATETIME, @endDate DATETIME, @type BIT', 
    @startDate, @endDate, @type;