我得到SQL错误转换数据类型varchar到日期

时间:2012-03-14 20:51:04

标签: sql-server datetime

我得到了

  

Msg 8114,Level 16,State 5,Procedure DetayliArama,Line 0 Error   将数据类型varchar转换为日期。

错误。有什么想法吗?

这是我的存储过程:

ALTER proc [dbo].[DetayliArama]
(
@ilktarih date = null,
@sontarih date = null,
@islem nvarchar(10) = null,
@birim int = null
)
as
declare @sorgu nvarchar (max)
set @sorgu = 'select KasaID,Aciklama,Tutar,Tarih,Islem,IsDeleted,KasalarID 
from KasaTable where IsDeleted=0 and KasalarID='+CONVERT(varchar(10),@birim)+' AND ' 
if (@islem is not null) 
    set @sorgu += 'Islem like ''%'+@islem+'%'' and '
if (@ilktarih is not null) 
    set @sorgu+='Tarih between '+convert(datetime,@ilktarih,120)+' 
        and '+convert(datetime,@sontarih ,120)+' and '                      
set @sorgu+='1=1 order by Tarih DESC'
exec (@sorgu)

1 个答案:

答案 0 :(得分:1)

(a)您需要用单引号括住日期/日期时间变量。否则,查询最终会像:

WHERE Tarih BETWEEN 2012-03-14 ...

将其作为数值表达式进行评估,因此最终成为:

WHERE Tarih BETWEEN 1995 ... -- and no that's not the year

(b)您不应该转换为DATETIME。尝试:

set @sorgu+='Tarih between '''+convert(CHAR(8),@ilktarih,112)+'''
  and '''+convert(CHAR(8),@sontarih ,112)+''' and '

但是我不明白你为什么要使用动态SQL。为什么不:

ALTER PROCEDURE [dbo].[DetayliArama]
  @ilktarih DATE         = NULL,
  @sontarih DATE         = NULL,
  @islem    NVARCHAR(10) = NULL,
  @birim    INT          = NULL
AS
BEGIN
   SET NOCOUNT ON;

    SELECT KasaID, Aciklama, Tutar, Tarih, Islem, IsDeleted, KasalarID 
    FROM dbo.KasaTable 
    WHERE IsDeleted = 0 
    AND KasalarID = @birim
    AND Islem LIKE COALESCE('%'+@islem+'%', Islem)
    AND Tarih BETWEEN COALESCE(@ilktarih, '19000101') 
        AND COALESCE(@sontarih, '20301231');
END
GO

在某些情况下,使用动态SQL可以更有效地避免因不同参数导致的错误计划。但是当你遇到它时我认为你应该处理它。