将数据类型nvarchar转换为datetime时出错?

时间:2012-03-28 03:40:46

标签: sql-server sql-server-2005

我正在使用sql server 2005,当我调用我的存储过程时,我收到此错误:

将数据类型nvarchar转换为datetime时出错。 那么如何传递我的日期时间来运行我的存储过程?

create procedure [dbo].[myProc]
@id as int,
@date as datetime
as
begin
    select id , DATEPART(day, @date)
    from myTable
    where convert(varchar,[date],101) =  convert(varchar,@date,101)
    and id =@id
end

DECLARE @return_value int

EXEC    @return_value = [dbo].[myProc]
        @id = 1,
        @date = N'getdate()'

SELECT  'Return Value' = @return_value

GO

1 个答案:

答案 0 :(得分:2)

您应该使用开放式日期范围,而不是将等式的两边都转换为区域字符串。

ALTER PROCEDURE [dbo].[myProc]
  @id   INT,
  @date DATETIME
AS
BEGIN
  SET NOCOUNT ON;

  SELECT id, DATEPART(DAY, @date)
    FROM dbo.myTable
    WHERE id = @id
    AND [date] >= DATEADD(DAY, 0, DATEDIFF(DAY, 0, @date))
    AND [date] <  DATEADD(DAY, 1, DATEDIFF(DAY, 0, @date));
END
GO

现在,您不能只将getdate()传递给存储过程调用(语法无效),您当然不能将其作为字符串传递。所以有两个选择。

(a)预先声明变量,将当前日期/时间分配给变量,并将变量传递给:

DECLARE @d DATETIME;
SET @d = GETDATE();
EXEC [dbo].[myProc] @id = 1, @date = @d;

(b)使参数成为可选参数,然后不要打扰传递该参数:

ALTER PROCEDURE [dbo].[myProc]
  @id   INT,
  @date DATETIME = NULL
AS
BEGIN
  SET NOCOUNT ON;

  SET @date = DATEADD(DAY, 0, DATEDIFF(DAY, 0, 
    COALESCE(@date, GETDATE())));

  SELECT id, DATEPART(DAY, @date)
    FROM dbo.myTable
    WHERE id = @id
    AND [date] >= @date
    AND [date] <  DATEADD(DAY, 1, @date);
END
GO

现在你的电话可以是:

EXEC dbo.myProc @id = 1;

此外,您不应将'single quotes'用于列别名 - 不推荐使用此语法。请改用[square brackets]