I get
Msg 8114, Level 16, State 5, Procedure DetayliArama, Line 0 Error
converting data type varchar to date.
error. Any ideas?
Here is my stored procedure:
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)
(a) you need to surround your date/datetime variables with single quotes. Otherwise the query ends up like:
Which gets evaluated as a numeric expression, so ends up being:
(b) you shouldn’t be converting to DATETIME. Try:
However I fail to see why you’re using dynamic SQL at all. Why not:
In some cases it can be more efficient to use dynamic SQL to avoid bad plans due to different parameters. But I think you should deal with that when you come across it.